package cn.com.dashihui.api.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.core.Action;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.com.dashihui.api.base.BaseService;
import cn.com.dashihui.api.common.GroupCode;
import cn.com.dashihui.api.common.OrderCode;
import cn.com.dashihui.api.common.SysConfig;
import cn.com.dashihui.api.common.UserCode;
import cn.com.dashihui.api.common.OrderCode.OrderDeliverState;
import cn.com.dashihui.api.dao.AuthSeller;
import cn.com.dashihui.api.dao.Goods;
import cn.com.dashihui.api.dao.Order;
import cn.com.dashihui.api.dao.OrderE;
import cn.com.dashihui.api.dao.OrderG;
import cn.com.dashihui.api.dao.OrderGLog;
import cn.com.dashihui.api.dao.OrderRefund;
import cn.com.dashihui.api.dao.OrderZ;
import cn.com.dashihui.api.dao.Seller;
import cn.com.dashihui.api.dao.Store;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.pay.refund.Refund;

public class OrderService  extends BaseService{
	
	/**
	 * 保存订单和订单清单
	 */
	public void saveE(OrderE order,String goodsid,String counts ,String sid,int company) throws Exception{
		String orderNum = order.getStr("orderNum");
		//保存订单
		order.save();
		//批量保存商品列表
		Object[][] params = new Object[1][10];
		String sql = "INSERT INTO t_bus_order_list(goodsid,orderNum,name,spec,shortinfo,price,thumb,count,amount,sellerId) VALUES(?,?,?,?,?,?,?,?,?,?)";
			Record goods=Db.findFirst("SELECT * FROM t_bus_ege_goods WHERE id=?",goodsid);
			Record rec = Db.findFirst("SELECT muchsellerPrice FROM t_bus_ege_goods_spec WHERE id=?",sid);
			Double price = rec.getDouble("muchsellerPrice");
			params[0][0]=goodsid;
			params[0][1]=orderNum;
			params[0][2]=goods.getStr("name");
			params[0][3]=sid;
			params[0][4]=goods.getStr("shortInfo");
			params[0][5]=price;
			params[0][6]=goods.getStr("thumb");
			params[0][7]=counts;
			params[0][8]=price*Integer.valueOf(counts);
			params[0][9]=company;
		Db.batch(sql, params,1);
	}
	
	/**
	 * 保存普通订单和订单清单
	 * @param order 订单
	 * @param goodsid  商品ID字符串
	 * @param counts 商品数量字符串
	 * @param sid 商品规格字符串
	 * @param isSpike 是否秒杀
	 * @param company 所属公司
	 * @throws Exception
	 */
	public void save(Order order,String goodsid,String counts ,String sid,int isSpike,int company) throws Exception{
		String orderNum = order.getStr("orderNum");
		//保存订单
		order.save();
		String[] goodsidArray = goodsid.split(",");
		String[] count = counts.split(",");
		String[] sids = sid.split(",");
		
		
		if(isSpike==1){
			List<Record> re = findPriceByid(sid);
			Double price = re.get(0).getDouble("saleprice");
			String name = re.get(0).getStr("title");
			//减去秒杀库存
			Record findSpikeByid = findSpikeByid(goodsid);
			int num = findSpikeByid.getInt("spikeLeft")-1;
			price = findSpikeByid.getDouble("spikePrice");
			Db.update("UPDATE t_spike_union SET spikeLeft=? WHERE goodsId=?",num,goodsid);
		}
		//批量保存商品列表
		Object[][] params = new Object[goodsidArray.length][26];
		String sql = "INSERT INTO t_bus_order_list(goodsid,orderNum,name,spec,shortinfo,price,thumb,count,amount,sellerId,"
				+ "isToker,onePoint,oneDetion,oneDcount,twoPoint,twoDetion,twoDcount,threePoint,threeDetion,"
				+ "threeDcount,fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,fiveDcount) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		for(int i=0;i<goodsidArray.length;i++){
			
			String goodsids = goodsidArray[i];
			Goods goods=Goods.me().findFirst("SELECT * FROM t_bus_goods WHERE id=?",goodsids);
			//根据ids查询拓客
			Record toker = Db.findFirst("SELECT tt.* FROM t_bus_goods_toker tt WHERE tt.state=1 AND tt.goodsId=?",goodsids);
			
			
			String specid = sids[i];
			List<Record> res =  findPriceByid(specid);
			Record re = res.get(0);
			Double price = re.getDouble("saleprice");
			String name = re.getStr("title");
			params[i][0]=goodsids;
			params[i][1]=orderNum;
			params[i][2]=name;
			params[i][3]=goods.getStr("spec");
			params[i][4]=re.getStr("title");
//			params[i][4]=goods.getStr("shortInfo");
			params[i][5]=price;
			params[i][6]=goods.getStr("thumb");
			params[i][7]=count[i];
			params[i][8]=price*Integer.valueOf(count[i]).intValue();
			params[i][9]=company;
			if(toker!=null){
				params[i][10]=1;
				params[i][11]=toker.getDouble("onePoint");
				params[i][12]=toker.getDouble("oneDetion");
				params[i][13]=toker.getDouble("oneDcount");
				params[i][14]=toker.getDouble("twoPoint");
				params[i][15]=toker.getDouble("twoDetion");
				params[i][16]=toker.getDouble("twoDcount");
				params[i][17]=toker.getDouble("threePoint");
				params[i][18]=toker.getDouble("threeDetion");
				params[i][19]=toker.getDouble("threeDcount");
				params[i][20]=toker.getDouble("fourPoint");
				params[i][21]=toker.getDouble("fourDetion");
				params[i][22]=toker.getDouble("fourDcount");
				params[i][23]=toker.getDouble("fivePoint");
				params[i][24]=toker.getDouble("fiveDetion");
				params[i][25]=toker.getDouble("fiveDcount");
			}else{
				params[i][10]=0;
				params[i][11]=0;
				params[i][12]=0;
				params[i][13]=0;
				params[i][14]=0;
				params[i][15]=0;
				params[i][16]=0;
				params[i][17]=0;
				params[i][18]=0;
				params[i][19]=0;
				params[i][20]=0;
				params[i][21]=0;
				params[i][22]=0;
				params[i][23]=0;
				params[i][24]=0;
				params[i][25]=0;
			}
		}
		Db.batch(sql, params, goodsidArray.length);
	}
	
	/**
	 * 保存在线充值订单
	 * @param order 订单
	 * @param company 用户所属公司
	 * @return
	 * @throws Exception
	 */
	@Before(Tx.class)
	public boolean saveZ(OrderZ order,int company) throws Exception{
		String orderNum = order.getStr("orderNum");
		//保存订单
		if (order.save()) {
			log(orderNum, 1, "用户"+order.getStr("userid"), "提交充值订单", "提交充值订单");
			
			int goodsid=order.getInt("goodsid");
			Record goods=Db.findFirst("SELECT * FROM t_bus_goods_ecard WHERE id=?",goodsid);
			Double price = order.getDouble("amount");
			
			
			String sql = "INSERT INTO t_bus_order_list(goodsid,orderNum,name,spec,shortinfo,price,thumb,count,amount,sellerId) VALUES(?,?,?,?,?,?,?,?,?,?)";
			Object[][] params = new Object[1][10];
				params[0][0]=goodsid;
				params[0][1]=orderNum;
				params[0][2]=goods.getStr("name");
				params[0][3]="";
				params[0][4]=goods.getStr("shortInfo");
				params[0][5]=price;
				params[0][6]=goods.getStr("thumb");
				params[0][7]=1;
				params[0][8]=price;
				params[0][9]=company;
			Db.batch(sql, params,1);
			return true;
		}else {
			return false;
		}
		
	}
	
	/**
	 * 用户查询各种状态的订单列表
	 */
	public Page<Record> findByPage(int storeid,int userid,int flag,int pageNum,int pageSize){
		if(flag==1){
			//1:待付款（“在线支付”、“未支付”、“正常”）
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id "
					+ "WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=? AND bo.payType=? AND bo.payState=? AND bo.orderState=? "
					+ "ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName ",sql,storeid,userid,OrderCode.OrderPayType.ON_LINE,OrderCode.OrderPayState.NO_PAY,OrderCode.OrderState.NORMAL);
		}else if(flag==2){
			//2：待发货（1：“在线支付+送货上门”、“已支付”、“未发货”、“正常”，2：“货到付款+送货上门”、“未发货”、“正常”）
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=?"
					+ " AND ((bo.payType=? AND bo.payState=?)"
					+ " OR bo.payType=?)"
					+ " AND bo.takeType=? AND bo.deliverState=? AND bo.orderState=?"
					+ " ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName ",sql,storeid,userid,
					OrderCode.OrderPayType.ON_LINE,OrderCode.OrderPayState.HAD_PAY,
					OrderCode.OrderPayType.ON_DELIVERY,
					OrderCode.OrderTakeType.DELIVER,OrderCode.OrderDeliverState.NO_DELIVER,OrderCode.OrderState.NORMAL);
		}else if(flag==3){
			//3：待收/取货（1：“送货上门”、“已发货”、“正常”，2：“在线支付+门店自取”、“已支付”、“正常”，3：“货到付款+门店自取”、“正常”）
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=?"
					+ " AND ((bo.takeType=? AND bo.deliverState=?)"
					+ " OR (bo.payType=? AND bo.payState=? AND bo.takeType=?)"
					+ " OR (bo.payType=? AND bo.takeType=?))"
					+ " AND bo.orderState=? ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName ",sql,storeid,userid,
					OrderCode.OrderTakeType.DELIVER,OrderCode.OrderDeliverState.HAD_DELIVER,
					OrderCode.OrderPayType.ON_LINE,OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderTakeType.TAKE_SELF,
					OrderCode.OrderPayType.ON_DELIVERY,OrderCode.OrderTakeType.TAKE_SELF,
					OrderCode.OrderState.NORMAL);
		}else if(flag==4){
			//4：已完成（“已完成”）
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=? AND bo.orderState=? ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName ",sql,storeid,userid,OrderCode.OrderState.FINISH);
		}else{
			//0：全部，不显示“删除”的订单
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=? AND bo.orderState!=? ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName ",sql,storeid,userid,OrderCode.OrderState.DELETE);
		}
	}
	
	public Page<Record> findByPage_v132(int storeid,int userid,int flag,int pageNum,int pageSize){
		if(flag==1){
			//1：全部，不显示“删除”的订单
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=? AND bo.orderState!=? ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName,(bo.amount - bo.redeemMoney) realPay ",sql,storeid,userid,OrderCode.OrderState.DELETE);
		}else if(flag==2){
			//2:待付款（“在线支付”、“未支付”、“正常”）
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=? AND bo.payType=? AND bo.payState=? AND bo.orderState=? ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName,(bo.amount - bo.redeemMoney) realPay ",sql,storeid,userid,OrderCode.OrderPayType.ON_LINE,OrderCode.OrderPayState.NO_PAY,OrderCode.OrderState.NORMAL);
		}else if(flag==3){
			//3：待收/取货（1：“在线支付”、“已支付”、“正常”，2：“货到付款”、“正常”）
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=?"
					+ " AND ((bo.payType=? AND bo.payState=?) OR bo.payType=?) AND bo.orderState=?"
					+ " ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName,(bo.amount - bo.redeemMoney) realPay ",sql,storeid,userid,
					OrderCode.OrderPayType.ON_LINE,OrderCode.OrderPayState.HAD_PAY,
					OrderCode.OrderPayType.ON_DELIVERY,OrderCode.OrderState.NORMAL);
		}else if(flag==4){
			//4：待评价（“已完成”、“未评价”）
			String sql = "FROM t_bus_order bo LEFT JOIN t_dict_store ds ON bo.storeid=ds.id WHERE (bo.storeid=? OR bo.isSelf=1) AND bo.userid=? AND bo.orderState=? AND bo.evalState=0 ORDER BY bo.createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT bo.*,ds.title storeName,(bo.amount - bo.redeemMoney) realPay ",sql,storeid,userid,OrderCode.OrderState.FINISH);
		}
		return null;
	}
	
	/**
	 * 根据合单号修改订单的支付渠道
	 * @return
	 */
	public int updateOrderByMergerNum(String mergerNum, int payMethod){
		return Db.update("update t_bus_order set payMethod=? where mergerNum=?", mergerNum, payMethod);
	}
	
	/**
	 * 根据普通单号查询出订单列表<br/>
	 * 排除已删除的订单
	 */
	public List<Order> getOrderListByMergerOrderNum(String orderNum){
		String sql = "SELECT * FROM t_bus_order WHERE orderNum=?  AND orderState!=? ";
		return Order.me().find(sql,orderNum,OrderCode.OrderState.DELETE);
	}
	
	/**
	 * 根据兑换单号查询出订单列表<br/>
	 * 排除已删除的订单
	 */
	public List<OrderE> getExchangeOrderListByMergerOrderNum(String orderNum){
		String sql = "SELECT * FROM t_bus_order_act WHERE orderNum=?  AND orderState!=?";
		return OrderE.me().find(sql,orderNum,OrderCode.OrderState.DELETE);
	}
	
	/**
	 * 根据充值单号查询出充值订单列表<br/>
	 * 排除已删除的订单
	 */
	public List<OrderZ> getRechangeOrderListByMergerOrderNum(String orderNum){
		String sql = "SELECT * FROM t_bus_order_ecard WHERE orderNum=?  AND orderState!=?";
		return OrderZ.me().find(sql,orderNum,OrderCode.OrderState.DELETE);
	}
	
	/**
	 * 根据用户ID和订单号查询出订单<br/>
	 * 排除已删除的订单
	 */
	public Order getOrderByOrderNum(int userid,String orderNum){
		String sql = "SELECT bo.*,l.charset ";
				sql += "FROM t_bus_order bo "
						+ " LEFT JOIN t_bus_order_logistics l ON l.orderCode=bo.orderNum  ";
				sql += "WHERE bo.userid=? AND bo.orderNum=? AND bo.orderState!=? ";
		return Order.me().findFirst(sql,userid,orderNum,OrderCode.OrderState.DELETE);

		
	}
	/**
	 * 根据用户ID和订单号查询出订单<br/>
	 * 排除已删除的订单
	 */
	public OrderE getExchangeOrderByOrderNum(int userid,String orderNum){
		String sql = "SELECT bo.*,l.charset ";
				sql += "FROM t_bus_order_act bo "
					+ " LEFT JOIN t_bus_order_logistics l ON l.orderCode=bo.orderNum  ";
				sql += "WHERE bo.userid=? AND bo.orderNum=? AND bo.orderState!=? ";
		return OrderE.me().findFirst(sql,userid,orderNum,OrderCode.OrderState.DELETE);

		
	}
	/**
	 * 根据用户ID和订单号查询出订单<br/>
	 * 排除已删除的订单
	 */
	public OrderG getGroupOrderByOrderNum(int userid,String orderNum){
		String sql = "SELECT bo.*,l.charset ";
				sql += "FROM t_bus_order_gb bo "
					+ " LEFT JOIN t_bus_order_logistics l ON l.orderCode=bo.orderNum  ";
				sql += "WHERE bo.userid=? AND bo.orderNum=? AND bo.orderState!=? ";
		return OrderG.me().findFirst(sql,userid,orderNum,OrderCode.OrderState.DELETE);

		
	}
	/**
	 * 根据用户ID和订单号查询出订单<br/>
	 * 排除已删除的订单
	 */
	public OrderE getExchangeOrdersByOrderNum(int userid,String orderNum){
		String sql = "SELECT bo.* ";
				sql += "FROM t_bus_order_act bo ";
				sql += "WHERE bo.userid=? AND bo.orderNum=? AND bo.orderState!=? ";
		return OrderE.me().findFirst(sql,userid,orderNum,OrderCode.OrderState.DELETE);

		
	}
	/**
	 * 根据用户ID和订单号查询出充值订单<br/>
	 * 排除已删除的订单
	 */
	public OrderZ getRechargeOrdersByOrderNum(int userid,String orderNum){
		String sql = "SELECT bo.* ";
				sql += "FROM t_bus_order_ecard bo ";
				sql += "WHERE bo.userid=? AND bo.orderNum=? AND bo.orderState!=? ";
		return OrderZ.me().findFirst(sql,userid,orderNum,OrderCode.OrderState.DELETE);

		
	}
	//根据id查询地址
	public Order getAddressByid(Order order) {
		String sql = "SELECT a.linkname,a.address,a.tel FROM t_bus_user_address a WHERE id=?";
		Record add = Db.findFirst(sql, order.getInt("addressid"));
		order.put("linkname", add.get("linkname"))
			.put("address", add.get("address"))
			.put("tel", add.get("tel"));
		return order;
	}
	//根据兑换id查询地址
	public OrderE getExchangeAddressByid(OrderE order) {
		String sql = "SELECT a.linkname,a.address,a.tel FROM t_bus_user_address a WHERE id=?";
		Record add = Db.findFirst(sql, order.getInt("addressid"));
		order.put("linkname", add.get("linkname"))
			.put("address", add.get("address"))
			.put("tel", add.get("tel"));
		return order;
	}
	//根据兑换id查询地址
	public OrderG getGroupAddressByid(OrderG order) {
		String sql = "SELECT a.linkname,a.address,a.tel FROM t_bus_user_address a WHERE id=?";
		Record add = Db.findFirst(sql, order.getInt("addressid"));
		order.put("linkname", add.get("linkname"))
			.put("address", add.get("address"))
			.put("tel", add.get("tel"));
		return order;
	}
	/**
	 * 根据用户ID和单号查询出订单列表<br/>
	 * 排除已删除的订单
	 */
	public Order getOrderListByMergerOrderNum(int userid,String orderNum){
		String sql = "SELECT * FROM t_bus_order WHERE userid=? AND orderNum=? AND orderState!=? ";
		return Order.me().findFirst(sql,userid,orderNum,OrderCode.OrderState.DELETE);
	}
	
	/**
	 * 根据订单号查询出普通订单<br/>
	 * 排除已删除的、已过期的订单
	 */
	public Order getOrderByOrderNum(String orderNum){
		return Order.me().findFirst("SELECT * FROM t_bus_order WHERE orderNum=? AND orderState!=? AND orderState!=?",orderNum,OrderCode.OrderState.DELETE,OrderCode.OrderState.EXPIRE);
	}
	
	/**
	 * 根据某一个订单的商品列表
	 */
	public List<Record> getGoodsListByOrderNum(String orderNum){
		String sql = "SELECT goodsid,name,price,thumb,spec,count,amount "
				+ "FROM t_bus_order_list "
				+ "WHERE orderNum=?";
		return Db.find(sql, orderNum);
	}
	/**
	 * 根据某一个订单的商品列表
	 */
	public List<Record> getExchanegByOrderNum(String orderNum){
		String sql = "SELECT ts.goodId,tg.name,ts.marketPrice,tg.thumb,ta.countnum,ta.amount,tg.shortInfo, "
				+ "ts.multipay,ts.opPoint,ts.opDedu,ts.opCoupon,ts.muchsellerPrice,ts.mpPoint,ts.mpDedu,ts.mpCoupon "
				+ "FROM t_bus_ege_goods_spec ts "
				+ "LEFT JOIN t_bus_ege_goods tg ON ts.goodId = tg.id "
				+ "LEFT JOIN t_bus_order_act ta ON ts.id=ta.specsid "
				+ "WHERE ta.orderNum=?";
		return Db.find(sql, orderNum);
	}
	
	/**
	 * 查询多个订单的商品列表
	 */
	public void getOrderGoodsList(List<Record> orderList){
		if(orderList!=null){
			//将所有订单的编号取出，以逗号分隔拼接
			String[] orderNumArr = new String[orderList.size()];
			for(int i=0;i<orderList.size();i++){
				orderNumArr[i] = "'"+orderList.get(i).getStr("orderNum")+"'";
			}
			//以订单编号为条件，查询所有订单的所有商品列表，并以订单号排序，方便遍历整理
			List<Record> allGoodsList = Db.find("SELECT orderNum,goodsid,name,price,thumb,spec,count,amount FROM t_bus_order_list WHERE orderNum IN ("+CommonKit.join(",", orderNumArr)+") ORDER BY orderNum");
			//遍历所有商品和订单，根据订单号将商品归类给对应的订单对象
			for(Record order : orderList){
				List<Record> goodsList = order.get("GOODSLIST");
				if(goodsList==null){
					goodsList = new ArrayList<Record>();
				}
				for(Record goods : allGoodsList){
					if(order.getStr("orderNum").equals(goods.getStr("orderNum"))){
						goodsList.add(goods);
					}
				}
				order.set("GOODSLIST",goodsList);
				order.set("STATEMENT",PropKit.get("constants.refund.statement"));
			}
		}
	}
	
	/**
	 * 查询退款订单列表
	 */
	public Page<Record> findRefundByPage(int storeid, int userid, int pageNum, int pageSize) {
		String sql = "SELECT bor.id,bor.refundnum,bor.type,bor.ordernum,bor.orderlistid,bor.amount,"
				+ "bor.state,bor.refusereason,bor.createdate,bor.updatedate,bo.amount orderamount";
		String sqlFrom = " FROM t_bus_order_refund bor INNER JOIN t_bus_order bo ON bor.orderNum = bo.orderNum AND (bo.storeid=? OR bo.isSelf=1) AND bo.userid = ? "
				+ " ORDER BY bor.createDate DESC";
		return Db.paginate(pageNum, pageSize, sql, sqlFrom, storeid, userid);
	}
	
	/**
	 * 根据订单号查询订单操作日志
	 */
	public List<Record> getLogListByOrderNum(String orderNum){
		return Db.find("SELECT type,user,action,content,createDate FROM t_bus_order_log WHERE orderNum=? ORDER BY createDate DESC", orderNum);
	}
	
	/**
	 * 用户催单
	 */
	@Before(Tx.class)
	public Order urgeOrder(int userid,String orderNum) throws Exception{
		if(Db.update("UPDATE t_bus_order SET urgeTimes=urgeTimes+1,urgeLastTime=now() WHERE userid=? AND orderNum=?",userid,orderNum)==1){
			return getOrderByOrderNum(orderNum);
		}
		throw new Exception("订单不存在");
	}
	
	/**
	 * 记录操作日志
	 * @throws Exception 
	 */
	public void log(String orderNum, int type, String user, String action, String content) throws Exception{
		if(Db.update("INSERT INTO t_bus_order_log(orderNum,type,user,action,content) VALUES(?,?,?,?,?)",orderNum,type,user,action,content)!=1){
			throw new Exception("日志记录失败");
		}
	}
	
	/**
	 * 记录兑换订单操作日志
	 * @throws Exception 
	 */
	public void logE(String orderNum, int type, String user, String action, String content) throws Exception{
		if(Db.update("INSERT INTO t_bus_order_log_act(orderNum,type,user,action,content) VALUES(?,?,?,?,?)",orderNum,type,user,action,content)!=1){
			throw new Exception("兑换日志记录失败");
		}
	}
	/**
	 * 
	 * @param order 订单
	 * @param user	用户
	 * @param action  微信  or  支付宝
	 * @param type	1 增加 2减少
	 * @param describe 用途描述
	 * @throws Exception 
	 */
//	@Before(Tx.class)
//	private void orderStateUpdateAndGive(Order order, User user, String action,String content, int paytype) throws Exception {
//		//获取订单号
//		String  orderNum = order.getStr("orderNum");
//		//规格id
//		int  userid = user.getInt("id");
//		//根据订单号和用户id更改order表的订单状态
//		Db.update("UPDATE t_bus_order SET paytype=?,payState = ?,orderState=?,payDate=? WHERE orderNum= ? AND userid= ?",paytype,2,2,new Date(),orderNum,userid);
//		//根据订单号和用户id记录订单日志
//		log(orderNum,2, user.getStr("name"),action,content);
//		//更改库存  
//		String sid = order.get("specsid");
//		String[] sids = sid.split(",");
//		String num = order.get("countnum");
//		String[] nums = num.split(",");
//		List<Record> rec = findPriceByid(sid);
//		for(Record re : rec){
//			for(int i=0;i<sids.length;i++){
//				if(re.getInt("id") == Integer.parseInt(sids[i])){
//					int stock = re.getInt("salestock") - Integer.parseInt(nums[i]);
//					Db.update("UPDATE t_bus_goods_sale SET salestock = ? WHERE id= ?",stock, Integer.parseInt(sids[i]));
//				}
//			}
//		}
//	}
	/**
	 * 普通订单开团资格，等级变更放在签收以后
	 * @param user  
	 * @param userid
	 * @param money
	 * @param user1
	 * @throws Exception
	 */
	private void orderDeal(User user, Double money) throws Exception {
		int userid = user.getInt("id");
		//查询是否有开团资格
		Double miniNumMoney=SysConfig.getMiniNumMoney();
		System.out.println("开团资格门槛:"+miniNumMoney);
		Double totalMoney=user.getDouble("totalMoney");
		Double sum = DoubleKit.add(totalMoney, money);
		if(sum.compareTo(miniNumMoney)>=0){
			System.out.println("去开通开团资格");
			if(Db.update("UPDATE t_bus_user SET createteam = 1 WHERE id=?",userid)!=1){
				throw new Exception("开团资格开通失败");
			}
		}
		//目前消费登记
		if(Db.update("UPDATE t_bus_user SET totalMoney = ? WHERE id=?",DoubleKit.add(totalMoney, money),userid)!=1){
			throw new Exception("总消费金额添加失败");
		}
		//  更改等级
		//目前消费登记
		int level =  user.getInt("taici");
		if(level!=0 && level!=7){
			//查询消费等级的下一等级对应积分
			Record levels = Db.findFirst("SELECT `toMoney` FROM t_bus_user_level_set WHERE `levelCode`=?",level+1);
			if(levels != null){
				Double levelnum = levels.getDouble("toMoney");
				//历史消费总金额
				Double moneySum =moneyChage(userid);
				if(levelnum.compareTo(moneySum)!=1){
					//更改用户表等级
					if(Db.update("UPDATE t_bus_user SET taici = ? WHERE id=?",level+1,userid)==1){
						//如果变化  t_bus_user_level_log   记录等级变化日志
						Db.update("INSERT INTO t_bus_user_level_log(userid,fromLevel,toLevel,flag,createDate) VALUES(?,?,?,?,?)", userid,level,level+1,1,new Date());
						
					}
					
				}
			}
			
		}
	}
	
	/**
	 * 兑换订单 花费积分
	 * @param order
	 * @param user1
	 * @throws Exception
	 */
	@Before(Tx.class)
	private void custSppoint(OrderE order,  User user) throws Exception {
		//获取userid 和  积分券信息
		String goodsName = order.getStr("goodsName");
		String orderNum = order.getStr("orderNum");
		int userid = user.getInt("id");
		Double money = order.getDouble("amount");
		String describe = "购买兑换商品";
		int type = 1;
		Double oldsp = user.getDouble("sppoint");
		Double oldjk = user.getDouble("jkpoint");
		Double oldjy = user.getDouble("jypoint");
		Double sppoint = DoubleKit.add(order.getDouble("sppoint"),oldsp);//商品积分
		Double jkpoint = DoubleKit.add(order.getDouble("jkpoint"),oldjk);  //抵扣券
		Double jypoint = DoubleKit.add(order.getDouble("jypoint"),oldjy);//惠券
		//更改用户表券信息
		String sql2 = "UPDATE t_bus_user SET sppoint = ?,jkpoint = ?,jypoint = ? WHERE id=?";
		if(Db.update(sql2,sppoint,jkpoint,jypoint,userid)!=1){
			throw new Exception("更改用户表失败失败");
		}
		//记录日志
		String sql3 = "INSERT INTO t_bus_user_value_log(userid,type,`describe`,fromOrderNum,"
				+ "createDate,sppoint,dedu,coupon,goodsName,sppointHistory,deduHistory,"
				+ "couponHistory,orderMoney) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
		if(Db.update(sql3,userid,type,describe,orderNum,new Date(),
				order.getDouble("sppoint"),order.getDouble("jkpoint"),
				order.getDouble("jypoint"),goodsName,oldsp,oldjk,oldjy,money)!=1){
			throw new Exception("记录日志失败");
		}
	}
	/**
	 * 普通订单
	 * @param order
	 * @param user1
	 */
	@Before(Tx.class)
	private void giveSppoint(Order order, User user1) {
		//获取userid 和  积分券信息
		String goodsName = order.getStr("goodsName");
		String orderNum = order.getStr("orderNum");
		int userid = user1.getInt("id");
		Double money = order.getDouble("amount");
		String describe = "购买普通商品";
		int type = 1;
		Double oldsp = user1.getDouble("sppoint");
		Double oldjk = user1.getDouble("jkpoint");
		Double oldjy = user1.getDouble("jypoint");
		Double sppoint = DoubleKit.add(order.getDouble("sppoint"),oldsp);//商品积分
		Double jkpoint = DoubleKit.add(order.getDouble("jkpoint"),oldjk);  //抵扣券
		Double jypoint = DoubleKit.add(order.getDouble("jypoint"),oldjy);//惠券
		
		//更改用户表券信息
		Db.update("UPDATE t_bus_user SET sppoint = ?,jkpoint = ?,jypoint = ? WHERE id=?",sppoint,jkpoint,jypoint,userid);
		//记录日志
		Db.update("INSERT INTO t_bus_user_value_log(userid,type,`describe`,fromOrderNum,createDate,sppoint,dedu,coupon,goodsName,sppointHistory,deduHistory,couponHistory,orderMoney) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",userid,type,describe,orderNum,new Date(),order.getDouble("sppoint"),order.getDouble("jkpoint"),order.getDouble("jypoint"),goodsName,oldsp,oldjk,oldjy,money);
	}
	/**
	 * 团购订单
	 * @param order
	 * @param user1
	 * @throws Exception
	 */
	@Before(Tx.class)
	private void giveSppoint(OrderG order, User user1) throws Exception {
		//获取userid 和  积分券信息
		String goodsName = order.getStr("goodsName");
		String orderNum = order.getStr("orderNum");
		int userid = user1.getInt("id");
		Double money = order.getDouble("amount");
		String describe = "购买团购商品";
		int type = 1;
		Double oldsp = user1.getDouble("sppoint");
		Double oldjk = user1.getDouble("jkpoint");
		Double oldjy = user1.getDouble("jypoint");
		Double sppoint = DoubleKit.add(order.getDouble("sppoint"),oldsp);//商品积分
		Double jkpoint = DoubleKit.add(order.getDouble("jkpoint"),oldjk);  //抵扣券
		Double jypoint = DoubleKit.add(order.getDouble("jypoint"),oldjy);//惠券
		
		//更改用户表券信息
		if(Db.update("UPDATE t_bus_user SET sppoint = ?,jkpoint = ?,jypoint = ? WHERE id=?",sppoint,jkpoint,jypoint,userid)!=1){
			throw new Exception("用户券信息更新失败");
		}
		//记录日志
		if(Db.update("INSERT INTO t_bus_user_value_log(userid,type,`describe`,fromOrderNum,"
				+ "createDate,sppoint,dedu,coupon,goodsName,sppointHistory,deduHistory,"
				+ "couponHistory,orderMoney) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
				userid,type,describe,orderNum,new Date(),order.getDouble("sppoint"),
				order.getDouble("jkpoint"),order.getDouble("jypoint"),goodsName,oldsp,oldjk,oldjy,money)!=1){
			throw new Exception("记录日志失败");
		}
	}
	/**
	 * 更改订单状态，记录日志，更改库存
	 * @param order 订单
	 * @param user	用户
	 * @param action  微信  or  支付宝
	 * @param type	1 增加 2减少
	 * @param describe 用途描述
	 * @throws Exception 
	 * @Return  1 成功 
	 */
	@Before(Tx.class)
	public int orderMoneyStateUpdateAndGive(Order order, User user, String action,String content, int paytype) throws Exception {
		//获取订单号
		String  orderNum = order.getStr("orderNum");
		//规格id
		int  userid = user.getInt("id");
		//根据订单号和用户id更改order表的订单状态
		if(Db.update("UPDATE t_bus_order SET paytype=?,payState = ?,orderState=?,payDate=? WHERE orderNum= ? AND userid= ?",paytype,2,2,new Date(),orderNum,userid)!=1){
			throw new Exception("更改订单失败");
		};
		//根据订单号和用户id记录订单日志
		log(orderNum,2, user.getStr("name"),action,content);
		
		UpdateOrderStock(order,user);
		
		return 1;
		
	}
	
	/**
	 * 更改库存
	 * @param order 订单
	 * @param user	用户
	 * @throws Exception 
	 * @Return  1 成功  
	 */
	@Before(Tx.class)
	public int UpdateOrderStock(Order order, User user) throws Exception {
		//更改库存  
		String sid = order.get("specsid");
		String[] sids = sid.split(",");
		String num = order.get("countnum");
		String[] nums = num.split(",");
		List<Record> rec = findPriceByid(sid);
		for(Record re : rec){
			for(int i=0;i<sids.length;i++){
				if(re.getInt("id") == Integer.parseInt(sids[i])){
					int stock = re.getInt("salestock") - Integer.parseInt(nums[i]);
					if(Db.update("UPDATE t_bus_goods_sale SET salestock = ? WHERE id= ?",stock, Integer.parseInt(sids[i]))!=1){
						throw new Exception("减少库存失败");
					}
				}
			}
		}
		
		return 1;
		
	}
	/**
	 * 
	 * @param order 兑换订单
	 * @param user	用户
	 * @param action  微信  or  支付宝
	 * @param type	1 增加 2减少
	 * @param describe 用途描述
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public int orderMoneyStateUpdateAndGive(OrderE order, User user, String action,String content, int paytype) throws Exception {
		//获取订单号
		String  orderNum = order.getStr("orderNum");
		//规格id
		int  userid = user.getInt("id");
		//根据订单号和用户id更改order表的订单状态
		String sql1 = "UPDATE t_bus_order_act SET paytype=?,payState = ?,orderState=?,payDate=? WHERE orderNum= ? AND userid= ?";
		if(Db.update(sql1,paytype,2,2,new Date(),orderNum,userid)!=1){
			throw new Exception("更改订单状态失败");
		}
		
		//根据订单号和用户id记录订单日志
		logE(orderNum,2, user.getStr("name"),action,content);
		
		//查询初始化信息
		User user1 = User.me().findById(userid);
		monryQuery(order,  user1);
		return 1;
	}
	@Before(Tx.class)
	public void monryQuery(OrderE order,User user1) throws Exception {
		//订单消费金额
		Double money = order.getDouble("amount");
		int  userid = user1.getInt("id");
		//消费积分
		custSppoint(order, user1);		
		//查询是否有开团资格
		Double miniNumMoney=SysConfig.getMiniNumMoney();
		System.out.println("开团资格门槛:"+miniNumMoney);
		Double totalMoney=user1.getDouble("totalMoney");
		Double newTotalMoney=DoubleKit.add(totalMoney,money);
		if(newTotalMoney.compareTo(miniNumMoney)>=0){
			System.out.println("去开通开团资格");
			if(Db.update("UPDATE t_bus_user SET createteam = 1 WHERE id=?",userid)!=1){
				throw new Exception("开团资格开通失败");
			}
		}
		//目前消费登记TODO
		if(Db.update("UPDATE t_bus_user SET totalMoney = ? WHERE id=?",newTotalMoney,userid)!=1){
			throw new Exception("总消费金额添加失败");
		}
		UpdateOrderEStock(order,user1);
	}
	
	/**
	 * 更改兑换订单库存  和修改等级
	 * @param order 兑换订单
	 * @param user	用户
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public int UpdateOrderEStock(OrderE order, User user) throws Exception {
		//规格id
		int  userid = user.getInt("id");
		//更改库存  
		String sid = order.get("specsid").toString();
		String[] sids = sid.split(",");
		String num = order.get("countnum").toString();
		String[] nums = num.split(",");
		List<Record> rec = findPriceByid(sid);
		for(Record re : rec){
			for(int i=0;i<sids.length;i++){
				if(re.getInt("id") == Integer.parseInt(sids[i])){
					int stock = re.getInt("salestock") - Integer.parseInt(nums[i]);
					if(Db.update("UPDATE t_bus_goods_sale SET salestock = ? WHERE id= ?",stock, Integer.parseInt(sids[i]))!=1){
						throw new Exception("更改库存失败");
					}
					
				}
			}
		}
		//  更改等级
		int level =  user.getInt("taici");
		if(level!=0){
			//查询消费等级的下一等级对应积分
			Record levels = Db.findFirst("SELECT `toMoney` FROM t_bus_user_level_set WHERE `levelCode`=?",level+1);
			if(levels!=null){
				Double levelnum = levels.getDouble("toMoney");
				
				//历史消费总金额
				Double moneySum =  moneyChage(userid);
				
				if(levelnum.compareTo(moneySum)!=1){
					//更改用户表等级
					if(Db.update("UPDATE t_bus_user SET taici = ? WHERE id=?",level+1,userid)==1){
						//如果变化  t_bus_user_level_log   记录等级变化日志
						if(Db.update("INSERT INTO t_bus_user_level_log(userid,fromLevel,toLevel,flag,createDate) "
								+ "VALUES(?,?,?,?,?)", userid,level,level+1,1,new Date())!=1){
							throw new Exception("记录等级变更失败");
						}
					}else{
						throw new Exception("更改等级失败");
					}
					
				}
			}
			
		}
		return 1;
	}
	
	/**
	 * 无支付回调的充值订单更新
	 * @param order 订单
	 * @param user	用户
	 * @param action  微信  or  支付宝
	 * @param type	1 增加 2减少
	 * @param describe 用途描述
	 * @throws Exception 
	 * @Return  1 成功  2 更改订单失败 3 用户券信息更新失败  4 减少库存失败 5记录日志失败  7 更改用户等级失败  8 记录等级变更失败
	 */
	@Before(Tx.class)
	public int orderMoneyStateUpdateAndGive(OrderZ order, User user, String action,String content, int type, String describe,int paytype) throws Exception {
		//获取订单号
		String  orderNum = order.getStr("orderNum");
		//规格id
		int  userid = user.getInt("id");
		//获取商品信息
		int goodsid=order.getInt("goodsid");
		Record goods=Db.findById("t_bus_goods_ecard", goodsid);
		int stock;
		if (goods!=null) {
			stock=goods.getInt("countnum")-1;
		}else {
			throw new Exception("查询商品失败");
		}
		//更改库存
		if(Db.update("UPDATE t_bus_goods_ecard SET countnum = ? WHERE id= ?",stock, goodsid)!=1){
			throw new Exception("减少库存失败");
		}
		//根据订单号和用户id更改order表的订单状态
		if(Db.update("UPDATE t_bus_order_ecard SET paytype=?,payState = ?,orderState=?,payDate=? WHERE orderNum= ? AND userid= ?",paytype,2,4,new Date(),orderNum,userid)!=1){
			throw new Exception("更改订单失败");
		};
		//根据订单号和用户id记录订单日志
		log(orderNum,2, user.getStr("name"),action,content);
		
		//获取商品名
		String goodsName = order.getStr("goodsName");
		//订单消费金额
		Double money = order.getDouble("amount");
		
		if (order.getDouble("sppoint")>0||order.getDouble("jkpoint")>0||order.getDouble("jypoint")>0) {
			//查询初始化信息
			Record user1 = Db.findById("t_bus_user", userid);
			Double oldsp = user1.getDouble("sppoint");
			Double oldjk = user1.getDouble("jkpoint");
			Double oldjy = user1.getDouble("jypoint");
			Double sppoint = DoubleKit.add(order.getDouble("sppoint"),oldsp);//商品积分
			Double jkpoint = DoubleKit.add(order.getDouble("jkpoint"),oldjk);  //抵扣券
			Double jypoint = DoubleKit.add(order.getDouble("jypoint"),oldjy);//惠券
			
			//更改用户表券信息
			if(Db.update("UPDATE t_bus_user SET sppoint = ?,jkpoint = ?,jypoint = ? WHERE id=?",sppoint,jkpoint,jypoint,userid)!=1){
				throw new Exception("用户券信息更新失败");
			}
			//记录日志
			if(Db.update("INSERT INTO t_bus_user_value_log(flag,userid,type,`describe`,fromOrderNum,createDate,sppoint,dedu,coupon,goodsName,sppointHistory,deduHistory,couponHistory,orderMoney) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",UserCode.UserValueLogFlag.CONSUME_FOURTEEN,userid,type,describe,orderNum,new Date(),order.getDouble("sppoint"),order.getDouble("jkpoint"),order.getDouble("jypoint"),goodsName,oldsp,oldjk,oldjy,money)!=1){
				throw new Exception("记录日志失败");
			}
		}
		///充值
		//变化前金额
		Double oldMoney = user.getDouble("money");
		//变化后金额
		Double newMoney = DoubleKit.add(oldMoney, money);
		
		Record re = new Record().set("userid", userid)
				.set("amount", money)
				.set("type", "1")
				.set("fromOrderNum", orderNum)
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.ADDMONEY)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney)
				.set("describe", "充值");
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)==1){
			if(!Db.save("t_bus_user_money", re)){
				throw new RuntimeException("记录money变化表失败"); 
			}
		}else {
			throw new RuntimeException("更改用户余额失败"); 
		}
		return 1;
		
	}
	
	/**
	 * 有支付回调通知的充值订单更新
	 * @param order 订单
	 * @param user	用户
	 * @param action  微信  or  支付宝
	 * @param type	1 增加 2减少
	 * @param describe 用途描述
	 * @throws Exception 
	 * @Return  1 成功  2 更改订单失败 3 用户券信息更新失败  4 减少库存失败 5记录日志失败  7 更改用户等级失败  8 记录等级变更失败
	 */
	@Before(Tx.class)
	public int orderMoneyStateUpdateAndGive(OrderZ order, User user, int type, String describe) throws Exception {
		//获取订单号
		String  orderNum = order.getStr("orderNum");
		//规格id
		int  userid = user.getInt("id");
		//获取商品信息
		int goodsid=order.getInt("goodsid");
		Record goods=Db.findById("t_bus_goods_ecard", goodsid);
		int stock;
		if (goods!=null) {
			stock=goods.getInt("countnum")-1;
		}else {
			throw new Exception("查询商品失败");
		}
		//更改库存
		if(Db.update("UPDATE t_bus_goods_ecard SET countnum = ? WHERE id= ?",stock, goodsid)!=1){
			throw new Exception("减少库存失败");
		}
		
		//获取商品名
		String goodsName = order.getStr("goodsName");
		//订单消费金额
		Double money = order.getDouble("amount");
		
		if (order.getDouble("sppoint")>0||order.getDouble("jkpoint")>0||order.getDouble("jypoint")>0) {
			//查询初始化信息
			Record user1 = Db.findById("t_bus_user", userid);
			Double oldsp = user1.getDouble("sppoint");
			Double oldjk = user1.getDouble("jkpoint");
			Double oldjy = user1.getDouble("jypoint");
			Double sppoint = DoubleKit.add(order.getDouble("sppoint"),oldsp);//商品积分
			Double jkpoint = DoubleKit.add(order.getDouble("jkpoint"),oldjk);  //抵扣券
			Double jypoint = DoubleKit.add(order.getDouble("jypoint"),oldjy);//惠券
			
			//更改用户表券信息
			if(Db.update("UPDATE t_bus_user SET sppoint = ?,jkpoint = ?,jypoint = ? WHERE id=?",sppoint,jkpoint,jypoint,userid)!=1){
				throw new Exception("用户券信息更新失败");
			}
			//记录财富日志
			if(Db.update("INSERT INTO t_bus_user_value_log(flag,userid,type,`describe`,fromOrderNum,createDate,sppoint,dedu,coupon,goodsName,sppointHistory,deduHistory,couponHistory,orderMoney) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",UserCode.UserValueLogFlag.CONSUME_FOURTEEN,userid,type,describe,orderNum,new Date(),order.getDouble("sppoint"),order.getDouble("jkpoint"),order.getDouble("jypoint"),goodsName,oldsp,oldjk,oldjy,money)!=1){
				throw new Exception("记录日志失败");
			}
		}
		///充值
		//变化前金额
		Double oldMoney = user.getDouble("money");
		//变化后金额
		Double newMoney = DoubleKit.add(oldMoney, money);
		
		Record re = new Record().set("userid", userid)
				.set("amount", money)
				.set("type", "1")
				.set("fromOrderNum", orderNum)
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.ADDMONEY)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney)
				.set("describe", "充值");
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)==1){
			if(!Db.save("t_bus_user_money", re)){
				throw new RuntimeException("记录money变化表失败"); 
			}
		}else {
			
			throw new RuntimeException("更改用户余额失败"); 
		}
		return 1;
		
	}
	
	
	
	/**
	 * 消费金额
	 * @param userid
	 * @return
	 */
	public double moneyChage(int userid){
		//查询该用户普通订单消费金额
		String sql1 = "SELECT SUM(amount) as custMoney  FROM t_bus_order WHERE payState=? AND orderState=? AND tuistate=? AND userid=? ";
		Record re1 = Db.findFirst(sql1,OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderPayState.HAD_PAY,0, userid);
		//查询该用户兑换订单消费金额
		String sql2 = "SELECT SUM(amount) as custMoney  FROM t_bus_order_act WHERE payState=? AND orderState=? AND tuistate=? AND userid=? ";
		Record re2 = Db.findFirst(sql2,OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderPayState.HAD_PAY,0, userid);
		Double moneyG = 0.00;
		Double moneyD = 0.00;
		if(re1.getDouble("custMoney")!=null){
			moneyG = re1.getDouble("custMoney");
		}
		if(re2.getDouble("custMoney")!=null){
			moneyD = re2.getDouble("custMoney");
		}
		return DoubleKit.add(moneyG, moneyD);
//		return Db.findFirst("SELECT SUM(money) as custMoney FROM t_bus_user_pay_orderid WHERE userid=? AND ischeck=1 ",userid);
		
	}
	

	
	/**
	 * 更新用户实惠
	 */
	public int updateUserMoney(int userid,double presentMoney, double previousMoney){
		return Db.update("UPDATE t_bus_user SET money = ? WHERE id=? AND money=?",presentMoney,userid,previousMoney);
	}
	
	/**
	 * 订单评价
	 */
	public boolean doEval(String orderNum, int userid, int eval1, int eval2, int eval3, String content){
		return Db.update("INSERT INTO t_bus_order_eval(orderNum,userid,eval1,eval2,eval3,content) VALUES(?,?,?,?,?,?)",orderNum,userid,eval1,eval2,eval3,content)==1;
	}
	
	/**
	 * 验证用户要购买的商品(店铺商品)
	 * 1.验证是否有商品已下架
	 * 2.验证是否有商品购买量已经超过了今日所限量
	 * 3.验证总金额是否与客户端的入参总金额相同
	 * @param goodsids 要验证的商品ID数组，以英文逗号分隔
	 * @param counts  要验证的商品的购买数量数组，以英文逗号分隔
	 * @param isRedeem  0  金额订单  1 兑换订单
	 * @return flag 验证结果，0：验证通过，1：有商品已下架，2：有商品已经超量，3：计算对不上  4 积分不足
	 */
	@Before(Tx.class)
	public int validate(int userid,String goodIds,String counts,Double amount,
			String sid,String isSpike,int isRedeem,String zsactivity,String zscouponnum,
			String zsdedunum,String zspointnum){
		//1.准备数据
		//邮费
		Double postAge = 0.00;
		Double postAgeFree = 0.00;
		try {
			postAge = SysConfig.getPostAge();
			postAgeFree = SysConfig.getPostAgeFree();
			
		} catch (Exception e) {
			return 3;
		}
		if(isRedeem == 1){
//			1.验证是否有商品已下架
			String sql = "SELECT tg.state,tg.pstate,ts.stockNum,ts.multipay, "
					+ "ts.opPoint,ts.opDedu,ts.opCoupon,ts.muchsellerPrice,ts.mpPoint, "
					+ "ts.mpDedu,ts.mpCoupon "
					+ "FROM t_bus_ege_goods_spec ts "
					+ "LEFT JOIN t_bus_ege_goods tg ON ts.goodId = tg.id "
					+ "WHERE ts.id=?";
			Record findFirst = Db.findFirst(sql,sid);
			
			
			if(findFirst.getInt("state")!=2){
				return 1;
			}
			if(findFirst.getInt("pstate")==2){
				return 2;  //售罄
			}
//			  2.验证是否有商品购买量已经超过了今日所限量
			int stock =  findFirst.getInt("stockNum");
			if(stock<Integer.parseInt(counts)){
				return 2;
			}
			Double count = 0.00;
			Double ot = null;
			Double ou = null;
			Double on = null;
			
//			  3.验证总金额是否与客户端的入参总金额相同
			User user = User.me().findFirst("SELECT sppoint,jkpoint,jypoint FROM t_bus_user WHERE id=?",userid);
			if(Integer.parseInt(zsactivity) ==2){
				ot = findFirst.getDouble("opPoint");//所需积分
				ou = findFirst.getDouble("opDedu");//所需抵扣券
				on = findFirst.getDouble("opCoupon");//所需优惠券
				
			}else if(Integer.parseInt(zsactivity) ==3){
				ot = findFirst.getDouble("mpPoint");//所需积分
				ou = findFirst.getDouble("mpDedu");//所需抵扣券
				on = findFirst.getDouble("mpCoupon");//所需优惠券
				Double price = findFirst.getDouble("muchsellerPrice");
				
				if(price.compareTo(count)!=0){
					//兑换加上邮费
					Double prices = DoubleKit.mul(price,Double.parseDouble(counts));
					if(prices.compareTo(postAgeFree)==-1){
						prices = DoubleKit.add(prices, postAge);
					}
					if(Double.compare(prices, amount)!=0){
						return 3;
					}
				}
			}
			String sqle = "SELECT SUM(sppoint) as sppoint,SUM(jypoint) as jypoint,SUM(jkpoint) as jkpoint "
					+ " FROM t_bus_order_act WHERE payState=? AND userid=? AND expireDate>? " ;
			OrderE ordere = OrderE.me().findFirst(sqle,1,userid,DatetimeKit.getFormatDate(null));
			System.out.println("66666666666666666666"+ordere);
			if(ot.compareTo(count)!=0){
				//校验积分计算是否正确
				if(0!=Double.compare(DoubleKit.mul(ot, Double.parseDouble(counts)),Double.parseDouble(zspointnum))){
					return 3;
				}
				
				double cust = Double.parseDouble(zspointnum);
				System.out.println("花费的积分："+cust);
				System.out.println("积分余额："+user.getDouble("sppoint"));
				System.out.println("是否有锁定的积分："+(ordere!=null && ordere.getDouble("sppoint") !=null));
				
				if ( ordere!=null && ordere.getDouble("sppoint") !=null ){
					System.out.println("锁定的积分："+ordere.getDouble("sppoint"));
					//花费的积分  - 锁定的积分（锁定积分是负数）
					cust = DoubleKit.sub(cust,ordere.getDouble("sppoint"));
				}
				//校验积分余额是否充足（余额 - 花费的）!=0.00
				count=0.00;
				if( count.compareTo(DoubleKit.sub(user.getDouble("sppoint"),cust )) > 0 ){
					return 4;
				}
				
			}
			if(ou.compareTo(count)!=0){
				if(0!=Double.compare(DoubleKit.mul(ou, Double.parseDouble(counts)), 
						Double.parseDouble(zsdedunum))){
					return 3;
				}
				double cust = Double.parseDouble(zsdedunum);
				if ( ordere!=null && ordere.getDouble("jkpoint") !=null  ){
					cust = DoubleKit.sub(cust,ordere.getDouble("jkpoint"));
				}
				count=0.00;
				if(count.compareTo(DoubleKit.sub(user.getDouble("jkpoint"), cust)) > 0){
					return 4;
				}
			}
			if(on.compareTo(count)!=0){
				if(0!=Double.compare(DoubleKit.mul(on, Double.parseDouble(counts)), 
						Double.parseDouble(zscouponnum))){
					return 3;
				}
				double cust = Double.parseDouble(zscouponnum);
				if ( ordere!=null && ordere.getDouble("jkpoint") !=null ){
					cust = DoubleKit.sub(cust,ordere.getDouble("jypoint"));
				}
				count=0.00;
				if(count.compareTo(DoubleKit.sub(user.getDouble("jypoint"), cust)) > 0){
					return 4;
				}
			}
		}else if(isRedeem == 0){

			//1.1.对goodsidArray和countArray转成数组，准备下一步进行遍历判断
			String[] goodsidArrayInpt = goodIds.split(","), countArrayInpt = counts.split(","),sidArrayInput = sid.split(",");
			//1.2.查询要验证的商品列表，并查出每个商品今日的销量（包括订单状态为正常的和已完成的，也就是只要下了单，没有取消、删除、过期，都算量）
			
			
			//查找该用户下今日所购该商品数
			//查询待付款未失效的订单总和
			String sql0 ="SELECT SUM(countnum) as num,goodsid FROM  v_orderstateCom_num1 "
					+ "WHERE  userid=? AND expireDate>? AND goodsid IN ("+goodIds+") ";
			//查询已付款的购买数总和
			String sql00 ="SELECT SUM(countnum) as num,goodsid FROM  v_orderstateCom_num2 "
					+ "WHERE userid=? AND goodsid IN ("+goodIds+")";
			List<Record> find01 = Db.find(sql0, userid,new Date());
			List<Record> find02 = Db.find(sql00,userid);
			
			Map<Integer,Integer> map = new HashMap<Integer,Integer>();
			if(find01!=null&&find01.size()>0){
				for(Record re : find01){
					Object o0 = re.get("num",0);
					Object o1 = re.get("goodsid",0);
					int count01 = Integer.parseInt(o0.toString());
					int count02 = Integer.parseInt(o1.toString());
					map.put(count02, count01);
				}
			}
			if(find02!=null&&find02.size()>0){
				for(Record re : find02){
				Object o0 = re.get("num",0);
				Object o1 = re.get("goodsid",0);
				int count01 = Integer.parseInt(o0.toString());
				int count02 = Integer.parseInt(o1.toString());
				Integer count03 = map.get(count02);
				if(count03==null){
					map.put(count02, count01);
				}else{
					map.put(count02, count03+count01);
				}
				
				}
			}
			
			
			if(Integer.parseInt(isSpike)==1){
				//如果是秒杀，
				//查询该商品的库存   总量  限购数
				Record findSpike = findSpikeByid(goodIds);
				//总限购数
				int Num = findSpike.getInt("spikeNum");
				//每人限购数
				int Numone = findSpike.getInt("limited");
				//秒杀剩余
				int stock = findSpike.getInt("spikeLeft");
				//秒杀价格
				Double price =  findSpike.getDouble("spikePrice");
				if(stock>0){
					//查找该用户下今日所购该秒杀商品数
					//查询代付款未失效的订单总和
					String sql1 ="SELECT SUM(countnum) as num FROM  v_orderstate1_num "
							+ "WHERE isSpike=1 AND userid=? AND expireDate>? AND goodsid=? ";
					//查询已付款的购买数总和
					String sql2 ="SELECT SUM(countnum) as num FROM  v_orderstate2_num "
							+ "WHERE isSpike=1 AND userid=? AND goodsid=?  ";
					Record find1 = Db.findFirst(sql1, userid,new Date(),goodIds);
					Record find2 = Db.findFirst(sql2,userid,goodIds);
					int count1 = 0;
					int count2 = 0;
					if(find1!=null){
						Object o = find1.get("num",0);
						count1 = (int) Double.parseDouble((o.toString()));
					}
					if(find2!=null){
						Object o = find2.get("num",0);
						count2 = (int) Double.parseDouble((o.toString()));
					}
					int count = count1+count2;
					if(count>=Numone){
						return 2;
					}
					//查找该用户下今日所购该秒杀商品数
					//查询代付款未失效的订单总和
					String sql3 ="SELECT SUM(countnum) as num FROM  v_orderstate1_num "
							+ "WHERE isSpike=1 AND expireDate>? AND goodsid=? ";
					//查询已付款的购买数总和
					String sql4 ="SELECT SUM(countnum) as num FROM  v_orderstate2_num "
							+ "WHERE isSpike=1  AND goodsid=?  ";
					Record find3 = Db.findFirst(sql3, new Date(),goodIds);
					Record find4 = Db.findFirst(sql4,goodIds);
					int count3 = 0;
					int count4 = 0;
					if(find3.getInt("num")!=null){
						count3 = find3.getInt("num");
					}
					if(find4.getInt("num")!=null){
						count4 = find4.getInt("num");
					}
					int count5 = count3+count4;
					if(count5>=Num){
						//超过今日上限
						return 2;
					}
				}else{
					return 2;
				}
				if(!(price.compareTo(postAgeFree)<0)){
					price = DoubleKit.add(price, postAge);
				}
				
				if(price.compareTo(amount)==0){
					return 0;
				}else{
					return 3;
				}
				
			}
			
			String sql = "SELECT A.id,A.buytype,A.name,A.state,A.buycount FROM t_bus_goods A"
					+ " WHERE A.id IN ("+goodIds+") ";
			List<Record> list = Db.find(sql);
			
			
			//查找规格价格
			List<Record> rec = findPriceByid(sid);
			Double amount1 = 0.00;
			for(Record goods : list){
				//2.验证
				//商品ID
				int id = goods.getInt("id");
				//商品类型
				int buytype = goods.getInt("buytype");  //1不限购  2 限购
				//商品限量
				int buycount = goods.getInt("buycount"); //限购数量
				//商品上下架状态
				int state = goods.getInt("state");
				//商品今日已购数量
				Integer count = map.get(id);
				if(count==null){
					count = 0;
				}
				//2.1.验证是否有商品已经下架
				if(state==3){
					//有商品状态为2：已下架时，返回验证结果
					return 1;
				}
				//2超出该商品没人限购数
				if(buytype==2&&count>buycount){
					return 2;
				}
				
				for(Record re : rec){
					for(int i=0;i<sidArrayInput.length;i++){
						int countInpt = Integer.valueOf(countArrayInpt[i]);
						if(Integer.parseInt(sidArrayInput[i])==re.getInt("id")){
							if((buytype == 2)&&(count+countInpt)>buycount){
								return 2;
							}
							break;
						}
					}
				}
				
			}
			//3 计算金额
			for(Record re : rec){
				for(int i=0;i<sidArrayInput.length;i++){
					int countInpt = Integer.valueOf(countArrayInpt[i]);
					if(Integer.parseInt(sidArrayInput[i])==re.getInt("id")){
						amount1 = DoubleKit.add(amount1,DoubleKit.mul(re.getDouble("saleprice"),countInpt));
						break;
					}
				}
			}
			
			//2.3.验证后台计算出来的总金额是否与客户端传进来的总金额相同
			//加上邮费
			if(amount.compareTo(postAgeFree)==-1){
				amount1 = DoubleKit.add(amount1, postAge);
			}
		
			
			System.out.println(">>>>>>>>>>>>>>>>>>>"+amount);
			System.out.println(">>>>>>>>>>>>>>>>>>>"+amount1);
			if(amount.compareTo(amount1)!=0){
				//如果不相同，则金额不匹配，返回验证结果
				return 3;
			}
		}
		//3.验证通过
		return 0;
	}
	
	/**
	 * 验证用户要购买的商品(店铺商品)
	 * 1.验证是否有商品已下架
	 * 2.验证是否有商品购买量已经超过了今日所限量
	 * 3.验证总金额是否与客户端的入参总金额相同
	 * @param goodsids 要验证的商品ID数组，以英文逗号分隔
	 * @param counts  要验证的商品的购买数量数组，以英文逗号分隔
	 * @param isRedeem  0  金额订单  1 兑换订单
	 * @return flag 验证结果，0：验证通过，1：有商品已下架，2：有商品已经超量，3：计算对不上  4 积分不足
	 */
	@Before(Tx.class)
	public int validate1(int userid,String goodIds,String counts,Double amount){
		//1.查询该商品
		Record goods=Db.findFirst("select * from t_bus_goods_ecard where id =?" ,goodIds);
		//2.验证后台计算出来的总金额是否与客户端传进来的总金额相同，以及商品状态
		if(amount.compareTo(goods.getDouble("sellprice"))!=0){
			return 3;
		}else if (goods.getInt("state")!=2||goods.getInt("pstate")!=1) {
			return 1;
		}
		//3.验证通过
		return 0;
	}
	
	/**
	 * 查找秒杀信息
	 * @param sid
	 * @return 
	 */
	private Record findSpikeByid(String goodsid) {
		return Db.findFirst("SELECT spikePrice,spikeNum,spikeLeft,limited FROM t_spike_union WHERE goodsId=?", goodsid);
	}

	/**
	 * 取消订单，保存日志，并保存退款单信息
	 * @param order 订单信息
	 * @param reason 取消原因
	 * @param payType 支付类型
	 * @param payState 支付状态
	 * @param orderNum 订单编号
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public void cancelOrder(Order order,String reason, int payType, int payState, String orderNum,String isSpike) throws Exception {
		//4.取消订单操作，并记录日志
		order.set("orderState", OrderCode.OrderState.NORMAL).set("reason", reason).set("expireDate", new Date());
		if(order.update()){
//			//4-1.判断该订单是否是“在线支付”和“已支付”
//			if(payType == OrderCode.OrderPayType.ON_LINE && payState == OrderCode.OrderPayState.HAD_PAY) {
//				//保存退款单信息
//				//生成退款类订单的订单编号，以大写字母T开头
//				String orderRefundNum = "T"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
//				if(!new OrderRefund()
//						.set("refundNum", orderRefundNum)
//						.set("orderNum", orderNum)
//						.set("type", OrderCode.RefundType.CANCEL_ORDER)
//						.set("amount", order.getDouble("amount"))
//						.save()){
//					throw new Exception("生成退款单失败！");
//				}
//			}
			if("1".equals(isSpike)){
				//如果是秒杀订单，释放库存
				int spikeid = order.getInt("spikeid");
				Record re = Db.findFirst("SELECT spikeLeft FROM t_spike_union WHERE id=?",spikeid);
				if(re==null){
					throw new Exception("该商品秒杀信息不存在！");
				}
				int spikeLeft = re.getInt("spikeLeft")+1;
				if(Db.update("UPDATE t_spike_union SET spikeLeft=? WHERE id=?",spikeLeft,spikeid )!=1){
					throw new Exception("释放库存失败！");
				}
			}
			//4-2.订单取消成功，记录订单操作日志并返回最新订单
			log(order.getStr("orderNum"),OrderCode.OrderLogType.CANCEL,"用户", OrderCode.OrderLogType.CANCEL_ACTION, "订单已取消");
			//查询订单的商品列表供页面展示
			order.put("goodsList", getGoodsListByOrderNum(order.getStr("orderNum")));
		} else {
			throw new Exception("订单取消失败！");
		}
	}
	/**
	 * 取消兑换订单，保存日志，并保存退款单信息
	 * @param order 订单信息
	 * @param reason 取消原因
	 * @param payType 支付类型
	 * @param payState 支付状态
	 * @param orderNum 订单编号
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public void cancelExchangeOrder(OrderE order,String reason, int payType, int payState, String orderNum) throws Exception {
		//4.取消订单操作，并记录日志
		order.set("orderState", OrderCode.OrderState.NORMAL).set("reason", reason).set("expireDate", new Date());
		if(order.update()){
//			//4-1.判断该订单是否是“在线支付”和“已支付”
//			if(payType == OrderCode.OrderPayType.ON_LINE && payState == OrderCode.OrderPayState.HAD_PAY) {
//				//保存退款单信息
//				//生成退款类订单的订单编号，以大写字母T开头
//				String orderRefundNum = "T"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
//				if(!new OrderRefund()
//						.set("refundNum", orderRefundNum)
//						.set("orderNum", orderNum)
//						.set("type", OrderCode.RefundType.CANCEL_ORDER)
//						.set("amount", order.getDouble("amount"))
//						.save()){
//					throw new Exception("生成退款单失败！");
//				}
//			}
			
			//4-2.订单取消成功，记录订单操作日志并返回最新订单
			logE(order.getStr("orderNum"),OrderCode.OrderLogType.CANCEL,"用户", OrderCode.OrderLogType.CANCEL_ACTION, "订单已取消");
			//查询订单的商品列表供页面展示
			order.put("goodsList", getGoodsListByOrderNum(order.getStr("orderNum")));
		} else {
			throw new Exception("订单取消失败！");
		}
	}
	/**
	 * 用户签收订单
	 */
	@Before(Tx.class)
	public void receiveOrder(Order order,User user) throws Exception {
		//更新订单状态
		order.set("orderState", OrderCode.OrderState.CANCEL).set("signDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
		if(order.update()){
			String orderNum = order.getStr("orderNum");
			log(order.getStr("orderNum"),OrderCode.OrderLogType.GET,"用户", OrderCode.OrderLogType.GET_ACTION, "已取货，感谢您的购物，欢迎再次光临！");
			//根据用户所购买的商品，进行拓客处理   赠送积分等
			
			giveSppoint(order,user);
			//升等级，开启开团权限
			orderDeal(user,order.getDouble("amount"));
			//赠送
			rebate(order);
		}else{
			throw new Exception("订单接收失败！");
		}
	}
	

	/**
	 * 用户签收兑换订单
	 */
	@Before(Tx.class)
	public void receiveExchangeOrder(OrderE order,User user) throws Exception {
		//更新订单状态
		order.set("orderState", OrderCode.OrderState.CANCEL).set("signDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
		if(order.update()){
			String orderNum = order.getStr("orderNum");
			//上门自取，用户取货
			logE(orderNum,OrderCode.OrderLogType.GET,"用户", OrderCode.OrderLogType.GET_ACTION, "已取货，感谢您的购物，欢迎再次光临！");
			//根据用户所购买的商品，进行拓客处理 TODO  赠送积分等
			
//			兑换订单不参与拓客
		}else{
			throw new Exception("订单接收失败！");
		}
	}
	
	
	//一级返利累加
//	rebate1[0] = DoubleKit.add(rebate1[0], onePoint);
//	rebate1[1] = DoubleKit.add(rebate1[1], oneDetion);
//	rebate1[2] = DoubleKit.add(rebate1[2], oneDcount);
//	//二级返利累加
//	rebate1[3] = DoubleKit.add(rebate1[3], twoPoint);
//	rebate1[4] = DoubleKit.add(rebate1[4], twoDetion);
//	rebate1[5] = DoubleKit.add(rebate1[5], twoDcount);
//	//营业部服务所得累加
//	rebate1[6] = DoubleKit.add(rebate1[6], threePoint);
//	rebate1[7] = DoubleKit.add(rebate1[7], threeDetion);
//	rebate1[8] = DoubleKit.add(rebate1[8], threeDcount);
//	
//	//分公司培训所得累加
//	rebate1[9] = DoubleKit.add(rebate1[9], fourPoint);
//	rebate1[10] = DoubleKit.add(rebate1[10], fourDetion);
//	rebate1[11] = DoubleKit.add(rebate1[11], fourDcount);
//	//公司管理所得累加
//	rebate1[12] = DoubleKit.add(rebate1[12], fivePoint);
//	rebate1[13] = DoubleKit.add(rebate1[13], fiveDetion);
//	rebate1[14] = DoubleKit.add(rebate1[14], fiveDcount);
	
	
	/**
	 * 拓客
	 * @param order
	 * @param user
	 * @throws Exception
	 */
	private void rebate(Order order) throws Exception{
		String orderNum = order.getStr("orderNum");
		//下单用户id
		int userid =order.getInt("userid");
		//下单用户
		User user = User.me().findById(userid);
		//查询订单商品列表
		List<Record> goodsList = Db.find("SELECT * FROM t_bus_order_list WHERE orderNum=?", order.getStr("orderNum"));
		
		//所购开启拓客商品总额
		double totalAmount = 0;
		
		//用户注册时邀请人ID
		int inviteUserid = user.getInt("inviteid");
		//直接邀请人
		User userInvite=null;
		//间接邀请人用户id
		int userInvite_UserId = 0;
		if (inviteUserid!=0) {
			userInvite = User.me().findById(inviteUserid);
			userInvite_UserId = userInvite.getInt("inviteid");
		}
	
		
		//归属于那个营业部 			//营业部在t_auth_admin_seller表中的id
		int toBossOneId = user.getInt("toBossOneId");
		//用户归属于那个分公司 	//分公司在t_dict_store表中的id
		int toBossTwoId = user.getInt("toBossTwoId");
		//用户归属于那个公司//公司在t_bus_seller表中的id
		int toBossThreeId = user.getInt("toBossThreeId");
		
		//拓客日志SQL
		String logSql = "INSERT INTO t_bus_order_toker_log(orderNum,goodsid,amount,onePoint,oneDetion,oneDcount,twoPoint,twoDetion,twoDcount,"
				+ "threePoint,threeDetion,threeDcount,fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,fiveDcount) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		
	
		
			//拓客日志列表1 
			//拓客分成2（用户有邀请人，一级、二级、所属营业部、分公司、公司分润）
			List<Object[]> logParams1 = new ArrayList<Object[]>();
			//拓客分成1（用户没有邀请人，所属营业部、分公司、公司分润）
			double[] rebate1 = new double[15];
			
			//订单多商品多分润实际累计日志
			List<Object[]> logParamsTotal = new ArrayList<Object[]>();
		/*	****************#########################**************装载对象****start*******##########################*******************************************/
			//遍历所有商品
			for(Record goods : goodsList){
				//商品是否参与拓客  0 不拓客，1拓客
				if(goods.getInt("isToker")==1){
					//商品id
					int goodsid = goods.getInt("goodsid");
					//商品总金额
					double amount = goods.getDouble("amount");
					
					//累计本单中所有开启返利的商品的消费金额
					totalAmount = DoubleKit.add(totalAmount, amount);
					
					//一级返利的积分值
					double onePoint = goods.getDouble("onePoint");
					//一级返利的抵扣券
					double oneDetion = goods.getDouble("oneDetion");
					//一级返利的惠券
					double oneDcount = goods.getDouble("oneDcount");
					
					//二级返利的积分值
					double twoPoint = goods.getDouble("twoPoint");
					//二级返利的抵扣券
					double twoDetion = goods.getDouble("twoDetion");
					//二级返利的惠券
					double twoDcount = goods.getDouble("twoDcount");
					
					//'营业部服务所得的积分值',
					double threePoint = goods.getDouble("threePoint");
					//'营业部服务所得的抵扣券',
					double threeDetion = goods.getDouble("threeDetion");
					//'营业部服务所得的惠券',
					double threeDcount = goods.getDouble("threeDcount");
					
					//'分公司培训所得的积分值'
					double fourPoint = goods.getDouble("fourPoint");
					// '分公司培训所得的抵扣券',
					double fourDetion = goods.getDouble("fourDetion");
					//'分公司培训所得的惠券',
					double fourDcount = goods.getDouble("fourDcount");
					
					//'公司管理所得的积分值',
					double fivePoint = goods.getDouble("fivePoint");
					//'公司管理所得的抵扣券',
					double fiveDetion = goods.getDouble("fiveDetion");
					//'公司管理所得的惠券',
					double fiveDcount = goods.getDouble("fiveDcount");
					
					
					
					//邀请人存在时
					if(inviteUserid!=0) {
						//一级返利累加
						rebate1[0] = DoubleKit.add(rebate1[0], onePoint);
						rebate1[1] = DoubleKit.add(rebate1[1], oneDetion);
						rebate1[2] = DoubleKit.add(rebate1[2], oneDcount);
						
						//间接邀请人存在时
						if (userInvite_UserId!=0) {
							//二级返利累加
							rebate1[3] = DoubleKit.add(rebate1[3], twoPoint);
							rebate1[4] = DoubleKit.add(rebate1[4], twoDetion);
							rebate1[5] = DoubleKit.add(rebate1[5], twoDcount);
						} else {
							//二级返利累加
							rebate1[3] = 0;
							rebate1[4] = 0;
							rebate1[5] = 0;
						}
					} else {//邀请人不存在
						//一级返利累加
						rebate1[0] = 0;
						rebate1[1] = 0;
						rebate1[2] = 0;
						//二级返利累加
						rebate1[3] = 0;
						rebate1[4] = 0;
						rebate1[5] = 0;
						 onePoint = 0;
						oneDetion = 0;
						oneDcount = 0;
						twoPoint = 0;
						twoDetion = 0;
						twoDcount = 0;
					}
					
					
					//如果所属营业部存在则累计
					if (toBossOneId!=0) {
						//营业部服务所得累加
						rebate1[6] = DoubleKit.add(rebate1[6], threePoint);
						rebate1[7] = DoubleKit.add(rebate1[7], threeDetion);
						rebate1[8] = DoubleKit.add(rebate1[8], threeDcount);
					} else {
						//营业部服务所得累加
						rebate1[6] = 0;
						rebate1[7] = 0;
						rebate1[8] = 0;
						threePoint = 0;
						threeDetion = 0;
						threeDcount = 0;
					}
					 
					//如果所属分公司存在 则累加
					if (toBossTwoId!=0) {
						//分公司培训所得累加
						rebate1[9] = DoubleKit.add(rebate1[9], fourPoint);
						rebate1[10] = DoubleKit.add(rebate1[10], fourDetion);
						rebate1[11] = DoubleKit.add(rebate1[11], fourDcount);
					} else {
						//分公司培训所得累加
						rebate1[9] = 0;
						rebate1[10] = 0;
						rebate1[11] = 0;
						fourPoint= 0;
						fourDetion= 0;
						 fourDcount= 0;
					}
					
					//如果所属公司存在 则累加
					if (toBossThreeId!=0) {
						//公司管理所得累加
						rebate1[12] = DoubleKit.add(rebate1[12], fivePoint);
						rebate1[13] = DoubleKit.add(rebate1[13], fiveDetion);
						rebate1[14] = DoubleKit.add(rebate1[14], fiveDcount);
					} else {
						//公司管理所得累加
						rebate1[12] = 0;
						rebate1[13] = 0;
						rebate1[14] = 0;
						 fivePoint = 0;
						 fiveDetion = 0;
						 fiveDcount = 0;
					}
				
					
					//邀请人存在时或不存在时订单里每个商品拓客日志
					
					logParams1.add(new Object[]{orderNum,goodsid,amount,onePoint,oneDetion,oneDcount,twoPoint,
								twoDetion,twoDcount,threePoint,threeDetion,threeDcount,fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,fiveDcount});
					
				}
			}
			
			//订单拓客日志SQL
			String logSqlTotal = "INSERT INTO t_bus_order_toker_user_log(orderNum,totalAmount,totalPoint,totalDetion,totalDcount,"
					+ "userid,oneUserid,twoUserid,threeUserid,fourUserid,"
					+ "fiveUserid,onePoint,oneDetion,oneDcount,twoPoint,"
					+ "twoDetion,twoDcount,threePoint,threeDetion,threeDcount,"
					+ "fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,"
					+ "fiveDcount) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";


			
			
			AuthSeller authSeller=null;//营业部对象
			Store store =null;//分公司对象
			Seller seller=null;//公司对象
			int threeUserid = 0;
			int fourUserid = 0;
			int fiveUserid = 0;
			
			User userAuthSeller=null;//营业部在t_bus_user表的对象
			User userStore =null;//分公司在t_bus_user表的对象
			User userSeller=null;//公司在t_bus_user表的对象
			
			//营业部对象
			if (toBossOneId!=0) {
				authSeller= AuthSeller.me().findById(toBossOneId);
				//在t_bus_user表的id
				threeUserid=authSeller.getInt("tokerUserid");
				userAuthSeller= User.me().findById(threeUserid);
			}
			//分公司对象
			if (toBossTwoId!=0) {
				store= Store.me().findById(toBossTwoId);
				//在t_bus_user表的id
				fourUserid = store.getInt("tokerUserid");
				userStore= User.me().findById(fourUserid);
			}
			//公司对象
			if (toBossThreeId!=0) {
				seller= Seller.me().findById(toBossThreeId);
				//在t_bus_user表的id
				fiveUserid = seller.getInt("tokerUserid");
				userSeller= User.me().findById(fiveUserid);
			}
			double totalPoint =DoubleKit.add(rebate1[0]+rebate1[3],rebate1[6]+rebate1[9]+rebate1[12]) ;
			double totalDetion =DoubleKit.add(rebate1[1]+rebate1[4],rebate1[7]+rebate1[10]+rebate1[13]) ;
			double totalDcount =DoubleKit.add(rebate1[2]+rebate1[5],rebate1[8]+rebate1[11]+rebate1[14]) ;
			
			//总订单不在记录商品标号
			logParamsTotal.add(new Object[]{orderNum,totalAmount,totalPoint,totalDetion,totalDcount,userid,inviteUserid,userInvite_UserId,threeUserid,fourUserid,fiveUserid,rebate1[0],rebate1[1],rebate1[2],rebate1[3],
					rebate1[4],rebate1[5],rebate1[6],rebate1[7],rebate1[8],rebate1[9],rebate1[10],rebate1[11],rebate1[12],rebate1[13],rebate1[14]});
			
			/*	****************#########################**************装载对象****end*******##########################*******************************************/
			
			//如果消费的返利商品金额为0，则不处理
			if(totalAmount==0)return;
			
			//用户没有邀请人时
			if(inviteUserid==0){
				//如果用户注册时没有邀请人，则本次购物所有返利将由营业部、公司、分公司享利
				//1.如果所属营业部不为空，修改营业部用户的积分、抵扣券、惠券
				
				//营业部对象 和营业部所在用户表t_bus_user的id不为空时
				if (toBossOneId!=0 &&threeUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[6],rebate1[7],rebate1[8],threeUserid)!=1){
						throw new Exception("用户（用户ID："+threeUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录营业部用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							threeUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_THREE,orderNum,totalAmount,
							rebate1[6],rebate1[7],rebate1[8],userAuthSeller.get("sppoint"),userAuthSeller.get("jkpoint"),userAuthSeller.get("jypoint"),
							1,"营业部服务奖励",new Date());
				}
				//分公司对象 和分公司所在用户表t_bus_user的id不为空时
				if (toBossTwoId!=0&&fourUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[9],rebate1[10],rebate1[11],fourUserid)!=1){
						throw new Exception("用户（用户ID："+fourUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录分公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fourUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FOUR,orderNum,totalAmount,
							rebate1[9],rebate1[10],rebate1[11],userStore.get("sppoint"),userStore.get("jkpoint"),userStore.get("jypoint"),
							1,"分公司培训奖励",new Date());
				}
				//公司对象 和公司所在用户表t_bus_user的id不为空时
				if (toBossThreeId!=0&&fiveUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[12],rebate1[13],rebate1[14],fiveUserid)!=1){
						throw new Exception("用户（用户ID："+fiveUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fiveUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FIVE,orderNum,totalAmount,
							rebate1[12],rebate1[13],rebate1[14],userSeller.get("sppoint"),userSeller.get("jkpoint"),userSeller.get("jypoint"),
							1,"公司管理奖励",new Date());
				}
				
			}else{
				
				
				//邀请人存在时
				if(inviteUserid!=0) {
					//一级返利累加
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[0],rebate1[1],rebate1[2],inviteUserid)!=1){
						throw new Exception("用户（用户ID："+inviteUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录直接邀请人用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							inviteUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_ONE,orderNum,totalAmount,
							rebate1[0],rebate1[1],rebate1[2],userInvite.get("sppoint"),userInvite.get("jkpoint"),userInvite.get("jypoint"),
							1,"邀请人奖励",new Date());
					
					//间接邀请人存在时
					if (userInvite_UserId!=0) {
						//间接邀请人对象
						User inviteUser2 = User.me().findById(userInvite_UserId);
						//二级返利累加
						//此处使用行锁定的方式更新，防止并发
						if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[3],rebate1[4],rebate1[5],userInvite_UserId)!=1){
							throw new Exception("用户（用户ID："+inviteUserid+"）更新积分、抵扣券、惠券时出错！");
						}
						//2.记录直接邀请人用户积分、抵扣券、惠券变动日志（记录订单号）
						Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
								+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
								+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
								userInvite_UserId,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_TWO,orderNum,totalAmount,
								rebate1[3],rebate1[4],rebate1[5],inviteUser2.get("sppoint"),inviteUser2.get("jkpoint"),inviteUser2.get("jypoint"),
								1,"间接邀请人奖励",new Date());
					} 
					
				}

				//如果用户注册时没有邀请人，则本次购物所有返利将由营业部、公司、分公司享利
				//1.如果所属营业部不为空，修改营业部用户的积分、抵扣券、惠券
				//营业部对象 和营业部所在用户表t_bus_user的id不为空时
				if (toBossOneId!=0 &&threeUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[6],rebate1[7],rebate1[8],threeUserid)!=1){
						throw new Exception("用户（用户ID："+threeUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录营业部用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							threeUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_THREE,orderNum,totalAmount,
							rebate1[6],rebate1[7],rebate1[8],userAuthSeller.get("sppoint"),userAuthSeller.get("jkpoint"),userAuthSeller.get("jypoint"),
							1,"营业部服务奖励",new Date());
				}
				//分公司对象 和分公司所在用户表t_bus_user的id不为空时
				if (toBossTwoId!=0&&fourUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[9],rebate1[10],rebate1[11],fourUserid)!=1){
						throw new Exception("用户（用户ID："+fourUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录分公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fourUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FOUR,orderNum,totalAmount,
							rebate1[9],rebate1[10],rebate1[11],userStore.get("sppoint"),userStore.get("jkpoint"),userStore.get("jypoint"),
							1,"分公司培训奖励",new Date());
				}
				//公司对象 和公司所在用户表t_bus_user的id不为空时
				if (toBossThreeId!=0&&fiveUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[12],rebate1[13],rebate1[14],fiveUserid)!=1){
						throw new Exception("用户（用户ID："+fiveUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fiveUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FIVE,orderNum,totalAmount,
							rebate1[12],rebate1[13],rebate1[14],userSeller.get("sppoint"),userSeller.get("jkpoint"),userSeller.get("jypoint"),
							1,"公司管理奖励",new Date());
				}
				
				
			}
			//3.记录拓客日志,已商品列表为主的
			Db.batch(logSql, parseParams(logParams1), logParams1.size());
			//3.记录拓客日志,已订单总额为主的日志
			Db.batch(logSqlTotal, parseParams(logParamsTotal), logParamsTotal.size());

	}
	


	
	/**
	 * 将list<object[]>集合转换为object[][]
	 * @param params list<object[]>集合
	 */
	private Object[][] parseParams(List<Object[]> params){
		if(params!=null){
			Object[][] result = new Object[params.size()][];
			for(int index = 0;index<params.size();index++){
				result[index] = params.get(index);
			}
			return result;
		}
		return null;
	}
	
	/**
	 * 处理实惠抵用订单金额情况
	 * @param selfOrder
	 * @param storeOrder
	 * @return forwardFlag 1:跳转到支付页面，2：跳转到订单列表
	 */
	@Before(Tx.class)
	public int doRedeem(Order selfOrder,String goodIds,
			String counts,int userid,int isRedeem,String sid,Double amount,int isSpike) throws Exception{
		int forwardFlag = 1;
		//查询用户信息
		User user = User.me().findById(userid);
		int company = user.getInt("toBossThreeId");
		double userMoney = user.get("money");
		//店铺订单抵用金额
		double storeRedeemMoney = 0;
		//自营订单抵用金额
		double selfRedeemMoney = 0;
//		String sql = "INSERT INTO t_bus_user_value_log(userid,amount,type,`describe`,`data`,fromOrderNum) VALUES(?,?,?,?,?,?)";
		/**
		 * 只有店铺商品
		 */
//		if(storeOrder != null && selfOrder == null){
//			double orderAmount = Double.valueOf(storeOrder.get("amount"));
//			//判断是否是在线支付
//			if(storeOrder.getInt("payType") == OrderCode.OrderPayType.ON_LINE){
//				if(isRedeem == 1 && userMoney > 0){
//					//订单金额大于用户实惠，抵用金额为用户实惠，用户实惠改为0(需要支付)
//					if(orderAmount > userMoney) {
//						storeRedeemMoney = userMoney;
//						if(updateUserMoney(userid,0,userMoney) == 1){
//							storeOrder.set("redeemMoney", storeRedeemMoney).set("isRedeem", "1");
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 1;
//					}
//					//订单金额等于用户实惠，抵用金额为用户实惠/订单金额，用户实惠改为0(不需要支付)
//					else if(orderAmount == userMoney){
//						if(updateUserMoney(userid,storeRedeemMoney,userMoney) == 1){
//							storeOrder.set("redeemMoney", storeRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 2;
//					}
//					//订单金额小于用户实惠，抵用金额为订单金额，用户实惠改为“用户实惠-订单金额”(不需要支付)
//					else if(orderAmount < userMoney){
//						storeRedeemMoney = orderAmount;
//						if(updateUserMoney(userid,DoubleKit.sub(userMoney, orderAmount),userMoney) == 1){
//							storeOrder.set("redeemMoney", storeRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 2;
//					}
//					if(Db.update(sql,userid,storeRedeemMoney,2,UserCode.UserValueLogFlag.CONSUME_REDEEM,"实惠抵用便利店订单金额","",0,storeOrder.getStr("orderNum"))!=1){
//						throw new Exception("记录用户实惠变化日志失败");
//					}
//				}
//			} else {
//				forwardFlag = 2;
//			}
//			//保存订单
//			save(storeOrder, storeGoodsIds.split(","), storeCounts.split(","));
//			if(storeOrder.getInt("payType")==OrderCode.OrderPayType.ON_LINE){
//				log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，请尽快支付");
//			}else{
//				log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，等待系统确认");
//			}
//		}else
		/**
		 * 只有自营商品
		 */
		if(selfOrder != null){
			double orderAmount = amount;
			//抵用标志==1,处理实惠抵用情况
			if(isRedeem == 1 && userMoney > 0){
				//订单金额大于用户实惠，抵用金额为用户实惠，用户实惠改为0(需要支付)
				if(orderAmount > userMoney) {
					selfRedeemMoney = userMoney;
					if(updateUserMoney(userid,0,userMoney) == 1){
						selfOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1");
					} else {
						throw new Exception("更新用户money失败");
					}
					forwardFlag = 1;
				}
				//订单金额等于用户实惠，抵用金额为用户实惠/订单金额，用户实惠改为0(不需要支付)
				else if(orderAmount == userMoney){
					if(updateUserMoney(userid,selfRedeemMoney,userMoney) == 1){
						selfOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
					} else {
						throw new Exception("更新用户money失败");
					}
					forwardFlag = 2;
				}
				//订单金额小于用户实惠，抵用金额为订单金额，用户实惠改为“用户实惠-订单金额”(不需要支付)
				else if(orderAmount < userMoney){
					selfRedeemMoney = orderAmount;
					if(updateUserMoney(userid,DoubleKit.sub(userMoney, orderAmount),userMoney) == 1){
						selfOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
					} else {
						throw new Exception("更新用户money失败");
					}
					forwardFlag = 2;
				}
			}
//			if(Db.update(sql,userid,selfRedeemMoney,2,"消费累计","",selfOrder.getStr("orderNum"))!=1){
//				throw new Exception("记录用户实惠变化日志失败");
//			}
			//保存订单
			save(selfOrder, goodIds, counts,sid,isSpike,company);
//			if(selfOrder.getInt("payType")==OrderCode.OrderPayType.ON_LINE){
			log(selfOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，请尽快支付");
//			}else{
//				log(selfOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，等待系统确认");
//			}
//		}else
		/**
		 * 店铺商品和自营商品同时存在
		 * 先抵用自营商品的金额，如果还有剩余，再抵用店铺商品的金额
		 */
//		if(storeOrder != null && selfOrder != null){
//			double storeAmount = Double.valueOf(storeOrder.getStr("amount"));
//			double selfAmount = Double.valueOf(selfOrder.getStr("amount"));
//			//抵用标志==1,处理实惠抵用情况
//			if(isRedeem == 1 && userMoney > 0){
//				//如果店铺订单的支付方式为在线支付，订单金额为“店铺订单金额+自营订单金额”
//				if(storeOrder.getInt("payType") == OrderCode.OrderPayType.ON_LINE){
//					//自营订单金额大于用户实惠，抵用金额为用户实惠，用户实惠改为0(需要支付)
//					if(selfAmount > userMoney) {
//						selfRedeemMoney = userMoney;
//						if(updateUserMoney(userid,0,userMoney) == 1){
//							selfOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1");
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 1;
//					}
//					//自营订单金额等于用户实惠，抵用金额为用户实惠/订单金额，用户实惠改为0(需要支付)
//					else if(selfAmount == userMoney){
//						if(updateUserMoney(userid,selfRedeemMoney,userMoney) == 1){
//							selfOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 1;
//					}
//					//自营订单金额小于用户实惠，抵用金额为自营订单金额，用户实惠改为“用户实惠-订单金额”，再把用户剩余实惠与店铺订单的金额进行比较
//					else if(selfAmount < userMoney){
//						selfRedeemMoney = selfAmount;
//						//减去自营订单金额后用户剩余实惠
//						double userSur经纪人Money = DoubleKit.sub(userMoney, selfAmount);
//						if(updateUserMoney(userid, userSur经纪人Money, userMoney) == 1){
//							selfOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						//店铺订单金额大于用户剩余实惠，抵用金额为用户剩余实惠，用户实惠改为0(需要支付)
//						if(storeAmount > userSur经纪人Money){
//							storeRedeemMoney = userSur经纪人Money;
//							if(updateUserMoney(userid,0,userSur经纪人Money) == 1){
//								storeOrder.set("redeemMoney", storeRedeemMoney).set("isRedeem", "1");
//							} else {
//								throw new Exception("更新用户money失败");
//							}
//							forwardFlag = 1;
//						}
//						//店铺订单金额等于用户剩余实惠，抵用金额为用户剩余实惠/订单金额，用户实惠改为0(不需要支付)
//						else if(storeAmount == userSur经纪人Money){
//							storeRedeemMoney = userMoney;
//							if(updateUserMoney(userid, 0, userSur经纪人Money) == 1){
//								storeOrder.set("redeemMoney", storeRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//							} else {
//								throw new Exception("更新用户money失败");
//							}
//							forwardFlag = 2;
//						}
//						//店铺订单金额小于用户剩余实惠，抵用金额为店铺订单金额，用户剩余实惠改为“用户剩余实惠-订单金额”(不需要支付)
//						else if(storeAmount < userSur经纪人Money){
//							storeRedeemMoney = storeAmount;
//							if(updateUserMoney(userid, DoubleKit.sub(userSur经纪人Money, storeRedeemMoney), userSur经纪人Money) == 1){
//								storeOrder.set("redeemMoney", storeRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//							} else {
//								throw new Exception("更新用户money失败");
//							}
//							forwardFlag = 2;
//						}
//					}
//				} else {
//					//订单金额大于用户实惠，抵用金额为用户实惠，用户实惠改为0
//					if(selfAmount > userMoney) {
//						selfRedeemMoney = userMoney;
//						if(updateUserMoney(userid,0,userMoney) == 1){
//							storeOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1");
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 1;
//					}
//					//订单金额等于用户实惠，抵用金额为用户实惠/订单金额，用户实惠改为0(不需要支付)
//					else if(selfAmount == userMoney){
//						if(updateUserMoney(userid,selfRedeemMoney,userMoney) == 1){
//							storeOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 2;
//					}
//					//订单金额小于用户实惠，抵用金额为订单金额，用户实惠改为“用户实惠-订单金额”(不需要支付)
//					else if(selfAmount < userMoney){
//						selfRedeemMoney = selfAmount;
//						if(updateUserMoney(userid,DoubleKit.sub(userMoney, selfAmount),userMoney) == 1){
//							storeOrder.set("redeemMoney", selfRedeemMoney).set("isRedeem", "1").set("payState", OrderCode.OrderPayState.HAD_PAY);
//						} else {
//							throw new Exception("更新用户money失败");
//						}
//						forwardFlag = 2;
//					}
//				}
//				if(Db.update(sql,userid,selfRedeemMoney,2,UserCode.UserValueLogFlag.CONSUME_REDEEM,"实惠抵用直营订单金额","",0,selfOrder.getStr("orderNum"))!=1){
//					throw new Exception("记录用户实惠变化日志失败");
//				}
//				if(Db.update(sql,userid,storeRedeemMoney,2,UserCode.UserValueLogFlag.CONSUME_REDEEM,"实惠抵用便利店订单金额","",0,storeOrder.get("orderNum"))!=1){
//					throw new Exception("记录用户实惠变化日志失败");
//				}
//			}
//			//保存店铺商品订单
//			save(storeOrder, storeGoodsIds.split(","), storeCounts.split(","));
//			//根据订单支付方式不同，记录日志不同
//			if(storeOrder.getInt("payType")==OrderCode.OrderPayType.ON_LINE){
//				log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，请尽快支付");
//			}else{
//				log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，等待系统确认");
//			}
//			//保存自营商品订单
//			save(selfOrder, selfGoodsIds.split(","), selfCounts.split(","));
//			log(selfOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，请尽快支付");
//		}
		
		
		}
		return forwardFlag;
	}
	/**
	 * 处理实惠抵用订单金额情况
	 * @param selfOrder
	 * @param storeOrder
	 * @return forwardFlag 1:跳转到支付页面，2：跳转到订单列表
	 */
	@Before(Tx.class)
	public int doRedeemE(OrderE selfOrder,String goodIds,
			String counts,int userid,String sid,Double amount) throws Exception{
		int forwardFlag = 1;
		//查询用户信息
		User user = User.me().findById(userid);
		int company = user.getInt("toBossThreeId");
		Double count = 0.00;
		if(selfOrder != null){
			//如果订单金额为0，只需要支付积分，那么就直接扣除，不用走支付页面
			if(count.compareTo(selfOrder.getDouble("amount"))==0){
				forwardFlag = 2;
				//保存订单
				selfOrder
				.set("payState", OrderCode.OrderPayState.HAD_PAY)
				.set("orderState", OrderCode.OrderState.FINISH)
				.set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
				saveE(selfOrder, goodIds, counts,sid,company);
				//获取userid 和  积分券信息
				//查询初始化信息
				Double oldsp = user.getDouble("sppoint");
				Double oldjk = user.getDouble("jkpoint");
				Double oldjy = user.getDouble("jypoint");
				Double sppoint = DoubleKit.add(selfOrder.getDouble("sppoint"),oldsp);//商品积分
				Double jkpoint = DoubleKit.add(selfOrder.getDouble("jkpoint"),oldjk);  //抵扣券
				Double jypoint = DoubleKit.add(selfOrder.getDouble("jypoint"),oldjy);//惠券
				//订单消费金额
				Double money = 0.00;
				
				//更改用户表券信息
				Db.update("UPDATE t_bus_user SET sppoint = ?,jkpoint = ?,jypoint = ? WHERE id=?",sppoint,jkpoint,jypoint,userid);
				// 更改库存
				Record rec = Db.findFirst("SELECT stockNum FROM t_bus_ege_goods_spec WHERE id = ?",Integer.parseInt(sid));
				int stock = rec.getInt("stockNum")-Integer.parseInt(counts);
				Db.update("UPDATE t_bus_ege_goods_spec SET stockNum = ? WHERE id= ?",stock, Integer.parseInt(sid));
				//  记录日志   
				logE(selfOrder.getStr("orderNum"),OrderCode.OrderLogType.PAY,"用户", OrderCode.OrderLogType.PAY_ACTION, "订单已支付，会尽快安排发货");
				Record goods=Db.findFirst("SELECT * FROM t_bus_ege_goods WHERE id=?",goodIds);
				//记录兑换金额变动明细
				Db.update("INSERT INTO t_bus_user_value_log(userid,type,`describe`,fromOrderNum,"
						+ "createDate,sppoint,dedu,coupon,goodsName,sppointHistory,deduHistory,"
						+ "couponHistory,orderMoney) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
						userid,1,"兑换商品",selfOrder.get("orderNum"),new Date(),selfOrder.getDouble("sppoint"),selfOrder.getDouble("jkpoint"),selfOrder.getDouble("jypoint"),goods.getStr("name"),oldsp,oldjk,oldjy,money);
				
			}else{
				//保存订单
				saveE(selfOrder, goodIds, counts,sid,company);
				logE(selfOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，请尽快支付");
			}
		}
		return forwardFlag;
	}
	//查询默认付款卡信息
	public Record findUserCard(Integer userid) {
		String sql = "SELECT c.*,b.bankCode "
				+ "FROM t_bus_user_card c "
				+ "INNER JOIN t_bus_user_bank b ON c.bankid = b.id "
				+ "WHERE 1=1 AND userid = ? AND isDefault = ?";
		return Db.findFirst(sql, userid , 1);
	}
	
	
	/**
	 * 查询兑换订单列表 FLAG 订单状态，0：全部，1:待付款，2：待收货，3：待评价 4：待分享，
	 * @return
	 */
	public List<Record> findExchangeOrderByFlag(Integer userid, int flag) {
		List<Record> list =null;
		if(flag == 0){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate  as startDateTime,o.expireDate,o.specsid,o.goodsid, "
					+" o.payDate,o.tuistate "
					+"FROM t_bus_order_act o "
					+"WHERE o.userid=? AND o.orderState!=5";
			list  = Db.find(sql, userid);
			
		}else if(flag == 4){
			//兑换订单无需分享
		}else if(flag == 2){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate,o.expireDate,o.specsid,o.goodsid, "
					+" o.payDate  as startDateTime,o.tuistate "
					+"FROM t_bus_order_act o "
					+"WHERE o.userid=? AND ( o.orderState=? OR o.orderState=6 ) ";
			list = Db.find(sql, userid,flag);
		}else if (flag == 1){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate  as startDateTime,o.expireDate,o.specsid,o.goodsid, "
					+" o.payDate,o.tuistate "
					+"FROM t_bus_order_act o "
					+"WHERE o.userid=? AND o.orderState=? AND (o.orderState!=1 OR o.expireDate>now()) ";
			
			list = Db.find(sql, userid,flag);
		}else {
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate  ,o.expireDate,o.specsid,o.goodsid, "
					+" o.payDate as startDateTime,o.tuistate "
					+"FROM t_bus_order_act o "
					+"WHERE o.userid=? AND o.orderState=? AND (o.orderState!=1 OR o.expireDate>now()) ";
			
			list = Db.find(sql, userid,flag);
		}
		return list;
	}
	/**
	 * 查询团购订单列表 FLAG 订单状态，0：全部，1:待付款，2：待收货，3：待评价 4：待分享，
	 * @return
	 */
	public List<Record> findGroupOrderByFlag(Integer userid, int flag) {
		List<Record> list =null;
		if(flag == 0){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate as startDateTime,o.expireDate,o.goodsid, "
					+" o.payDate,o.tuistate "
					+"FROM t_bus_order_gb o "
					+"WHERE o.userid=? AND o.orderState!=5";
			list  = Db.find(sql, userid);
			
		}else if(flag == 4){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate,o.expireDate,o.goodsid,o.userid, "
					+" o.payDate   as startDateTime,o.tuistate "
					+"FROM t_bus_order_gb o "
					+ " LEFT JOIN t_bus_goods g ON o.goodsid=g.id "
					+"WHERE o.userid=? AND o.isFree=0 "
					+ " AND g.state=2  AND o.orderState>1 AND o.orderState!=5 AND o.buyNum!=1 AND o.isLeader!=1 ";
			list = Db.find(sql, userid);
		}else if(flag == 2){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate,o.expireDate,o.goodsid, "
					+" o.payDate   as startDateTime,o.tuistate "
					+"FROM t_bus_order_gb o "
					+"WHERE o.userid=? AND ( o.orderState=? OR o.orderState=6 ) ";
			list = Db.find(sql, userid,flag);
		}else if (flag==1){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate   as startDateTime,o.expireDate,o.goodsid, "
					+" o.payDate,o.tuistate "
					+"FROM t_bus_order_gb o "
					+"WHERE o.userid=? AND o.orderState=? AND (o.orderState!=1 OR o.expireDate>now()) ";
			
			list = Db.find(sql, userid,flag);
		}else{
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.orderState,o.startDate,o.expireDate,o.goodsid, "
					+" o.payDate   as startDateTime,o.tuistate "
					+"FROM t_bus_order_gb o "
					+"WHERE o.userid=? AND o.orderState=? AND (o.orderState!=1 OR o.expireDate>now()) ";
			
			list = Db.find(sql, userid,flag);
		}
		return list;
	}
	/**
	 * 查询普通订单各种状态的数量
	 * @param userid
	 * @return
	 */
	public List<Record> findOrderNum(Integer userid) {
		String sql = "select tbo.delstate,tbo.orderState,count(1) as num from t_bus_order tbo where tbo.userid=? AND (tbo.orderState!=1 OR tbo.expireDate>now()) group by tbo.orderState;";
		return Db.find(sql,userid);
	}
	
	/**
	 * 查询兑换订单各种状态的数量
	 * @param userid
	 * @return
	 */
	public List<Record> findExchangeOrderNum(Integer userid) {
		String sql = "select tboa.orderState,count(1) as num from t_bus_order_act tboa where tboa.userid=? AND (tboa.orderState!=1 OR tboa.expireDate>now()) group by tboa.orderState;";
		return Db.find(sql, userid);
	}
	/**
	 * 查询团购订单各种状态的数量
	 * @param userid
	 * @return
	 */
	public List<Record> findGroupBuyOrderNum(Integer userid) {
		String sql = "select tboa.orderState,count(1) as num from t_bus_order_gb tboa where tboa.userid=? AND (tboa.orderState!=1 OR tboa.expireDate>now()) group by tboa.orderState;";
		return Db.find(sql, userid);
	}
	/**
	 * 查询团购订单待分享的数量
	 * @param userid
	 * @return
	 */
	public Record findOrderNumShare(Integer userid) {
		String sql = "select count(1) as num from t_bus_order_gb tboa "
				+ " LEFT JOIN t_bus_goods g ON g.id=tboa.goodsid "
				+ " where tboa.userid=? AND tboa.isFree=0 "
				+ " AND g.state=2 AND tboa.orderState>1 AND tboa.orderState!=5 AND tboa.buyNum!=1 AND tboa.isLeader!=1 ";
		return Db.findFirst(sql, userid);
	}
	
	/**
	 * 查询普通会员订单总表
	 * @param userid
	 * @param flag 0：全部，1:待付款，2：待收货，3：待评价 4：待分享，
	 * @return 
	 * @return
	 */
	public List<Record> findByFlag(Integer userid, int flag) {
		List<Record> list =null;
		if(flag == 0){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.payState,o.orderState,o.startDate as startDateTime,o.expireDate,o.isSpike, "
					+" o.payDate,o.tuistate "
					+"FROM t_bus_order o "
					+"WHERE o.userid=? AND o.orderState!=5   ";
			list  = Db.find(sql, userid);
			
		}else if(flag == 4){
			//普通订单无需分享
		}else if(flag == 2){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.payState,o.orderState,o.startDate,o.expireDate,o.isSpike, "
					+" o.payDate as startDateTime,o.tuistate "
					+"FROM t_bus_order o "
					+"WHERE o.userid=? AND ( o.orderState=? OR o.orderState=6 )  AND o.orderState!=4 ";
			list = Db.find(sql, userid,flag);
		}else if (flag==1){
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.payState,o.orderState,o.startDate as startDateTime,o.expireDate,o.isSpike, "
					+" o.payDate,o.tuistate "
					+"FROM t_bus_order o "
					+"WHERE o.userid=? AND o.orderState=?  AND o.orderState!=4 AND (o.orderState!=1 OR o.expireDate>now()) ";
			
			list = Db.find(sql, userid,flag);
		}else {
			String sql = "SELECT o.id,o.orderNum,o.amount,o.countnum, "
					+ "o.payState ,o.orderState,o.startDate,o.expireDate,o.isSpike, "
					+" o.payDate  as startDateTime,o.tuistate "
					+"FROM t_bus_order o "
					+"WHERE o.userid=? AND o.orderState=?  AND o.orderState!=4 AND (o.orderState!=1 OR o.expireDate>now()) ";
			
			list = Db.find(sql, userid,flag);
		}
		return list;
	}
	public List<Record> findExchangeByid(int goodid,int specid){
		String sql = "SELECT tg.id,tg.name,tg.thumb,ts.goodId as goodsid, "
				+ "tg.shortinfo,ts.marketPrice,ts.multipay,ts.opPoint,ts.opDedu,ts.opCoupon, "
				+ "ts.muchsellerPrice,ts.mpPoint,ts.mpDedu,ts.mpCoupon "
				+"FROM t_bus_ege_goods_spec ts "
				+ "LEFT JOIN t_bus_ege_goods tg ON ts.goodId=tg.id "
				+"WHERE tg.id = ? AND ts.id = ? ";
		return Db.find(sql,goodid,specid);
	}
	
	//查找详细列表
	public List<Record> findListByNum(String orderNum) {
		String sql = "SELECT l.goodsid,l.name,l.price,l.thumb, "
				+ "l.spec,l.shortinfo,l.count "
				+"FROM t_bus_order_list l "
				+"WHERE orderNum=? ";
		return Db.find(sql, orderNum);
	}

	public List<Record> findPriceByid(String sid) {
		return Db.find("SELECT id,`goodsid`,`saleprice`,`salestock`,`title` FROM t_bus_goods_sale WHERE id IN ("+sid+")");
	}
	/**
	 * 保存提现信息
	 * @param record
	 */
	public int saveMoneyOut(Record record) {
		if(Db.save("t_bus_pay_banknoout", record)){
			return 1;
		}
		return 0;	
	}
	/**
	 * 查询提现记录
	 * @param bussSeqNo
	 * @return 
	 */
	public Record findMoneyOutByBussSeqNo(String bussSeqNo) {
		return Db.findFirst("SELECT BussSeqNo,AcctNo, FROM t_bus_pay_banknoout WHERE BussSeqNo=?", bussSeqNo);
	}
	/**
	 * 保存
	 * @param record
	 * @param userid
	 * @return 1  成功 2查找用户信息失败 3  更改用户余额失败 4 记录失败
	 */
	@Before(Tx.class)
	public int doRedem(Record record, int userid) {
		//查询用户信息
		User user = User.me().findFirst("SELECT id,money FROM t_bus_user WHERE id=?", userid);
		if(user==null){
			return 2;
		}
		//用户余额变动
		//变化前金额
		Double oldMoney = user.getDouble("money");
			//增加的金额
		Double addMoney = record.getDouble("TranAmount");
			//变化后金额
		Double newMoney = DoubleKit.sub(oldMoney, addMoney);
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)!=1){
			return 2;
		}
		//t_bus_user_money 记录
		Record rec = new Record().set("userid", userid)
				.set("amount", addMoney)
				.set("type", 2)
				.set("describe", "提现")
				.set("fromOrderNum", record.get("OrderNumber"))
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.SAVEMONEY)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney);
		if(!Db.update("t_bus_user_money", rec)){
			return 4;
		}
		//创建表记录record
		if(!Db.update("t_bus_pay_outlog_detail", record)){
			return 4;
		}
		return 1;
	}
	/**
	 * 根据id查询银行卡信息
	 * @param userid
	 * @return 
	 */
	public Record findUserCardById(int userid) {
		String sql = "SELECT tc.id,tc.userid,tc.custName,tc.phoneNo,tc.cardNo,tc.idNo, "
				+ "tc.bankSite,tc.province,tc.city,tb.bankNo FROM "
				+ "t_bus_user_card tc "
				+ "LEFT JOIN t_bus_user_bankno tb ON tb.id=tc.bankNoId "
				+ "WHERE tc.userid=?";
		return Db.findFirst(sql, userid);
	}
	/**
	 * 查询用户信息
	 * @param userid
	 * @return
	 */
	public User findUserByid(int userid) {
		return User.me().findById(userid);
	}
	/**
	 * 普通订单余额付款
	 * @param user
	 * @param amount
	 * @return 1  成功  2  更改用户余额失败 3记录money变化表失败
	 */
	@Before(Tx.class)
	public int chanegMoney (User user, double amount,String orderNum,Order order) throws Exception{
		int userid = user.getInt("id");
		//变化前金额
		Double oldMoney = user.getDouble("money");
			//增加的金额
		Double addMoney = amount;
			//变化后金额
		Double newMoney = DoubleKit.sub(oldMoney, addMoney);
		
		Record re = new Record().set("userid", userid)
				.set("amount", amount)
				.set("type", "2")
				.set("fromOrderNum", orderNum)
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.GOODORDER)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney)
				.set("describe", "购买商品");
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)==1){
			if(Db.save("t_bus_user_money", re)){
				if (order.set("orderState", OrderCode.OrderPayState.HAD_PAY).set("payState", OrderCode.OrderPayState.HAD_PAY).set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update()) {
					log(order.getStr("orderNum"),OrderCode.OrderLogType.PAY,"用户", OrderCode.OrderLogType.PAY_ACTION, "订单支付成功，等待系统确认");
					return 1;
				}
				throw new RuntimeException("更改订单状态失败"); 
			}
			throw new RuntimeException("记录money变化表失败"); 
		}
		throw new RuntimeException("更改用户余额失败"); 
	}
	/**
	 * 兑换订单余额付款  TODO
	 * @param user
	 * @param amount
	 * @return 1  成功  2  更改用户余额失败 3记录money变化表失败
	 */
	@Before(Tx.class)
	public int chanegMoney (User user, double amount,String orderNum,OrderE order) throws Exception{
		int userid = user.getInt("id");
		//变化前金额
		Double oldMoney = user.getDouble("money");
			//增加的金额
		Double addMoney = amount;
			//变化后金额
		Double newMoney = DoubleKit.sub(oldMoney, addMoney);
		
		Record re = new Record().set("userid", userid)
				.set("amount", amount)
				.set("type", "2")
				.set("fromOrderNum", orderNum)
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.GOODORDER)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney)
				.set("describe", "购买商品");
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)==1){
			if(Db.save("t_bus_user_money", re)){
				if (order.set("orderState", OrderCode.OrderPayState.HAD_PAY).set("payState", OrderCode.OrderPayState.HAD_PAY).set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update()) {
					log(order.getStr("orderNum"),OrderCode.OrderLogType.PAY,"用户", OrderCode.OrderLogType.PAY_ACTION, "订单支付成功，等待系统确认");
					return 1;
				}
				
			}
			throw new RuntimeException("记录money变化表失败"); 
		}
		throw new RuntimeException("更改用户余额失败"); 
	}
	/**
	 * 充值订单余额付款
	 * @param user
	 * @param amount
	 * @return 1  成功  2  更改用户余额失败 3记录money变化表失败
	 */
	@Before(Tx.class)
	public int chanegMoney (User user, double amount,String orderNum,OrderZ order) throws Exception{
		int userid = user.getInt("id");
		//变化前金额
		Double oldMoney = user.getDouble("money");
			//增加的金额
		Double addMoney = amount;
			//变化后金额
		Double newMoney = DoubleKit.sub(oldMoney, addMoney);
		
		Record re = new Record().set("userid", userid)
				.set("amount", amount)
				.set("type", "2")
				.set("fromOrderNum", orderNum)
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.GOODORDER)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney)
				.set("describe", "购买商品");
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,userid)==1){
			if(Db.save("t_bus_user_money", re)){
				if (order.set("orderState", OrderCode.OrderPayState.HAD_PAY).set("payState", OrderCode.OrderPayState.HAD_PAY).set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update()) {
					log(order.getStr("orderNum"),OrderCode.OrderLogType.PAY,"用户", OrderCode.OrderLogType.PAY_ACTION, "订单支付成功，等待系统确认");
					return 1;
				}
				throw new RuntimeException("更改订单状态失败"); 
			}
			throw new RuntimeException("记录money变化表失败"); 
		}
		throw new RuntimeException("更改用户余额失败"); 
	}
	/**
	 * 每次查询余额，更新用户余额
	 * @return 
	 */
	public int saveMoneyUp(Double money ,int id) {
		return Db.update("UPDATE t_bus_user SET money=? WHERE id=?", money,id);
	}
	/**
	 * 定时更新秒杀订单，更改库存信息
	 */
	@Before(Tx.class)
	public void changeSpike() throws Exception{
		//获取现在时间
		String nowdate = DatetimeKit.getFormatDate("");
		//获取60秒前的时间
		String olddate = DatetimeKit.getIntervalFormatDateb(1000*60,"");
		//查找出过期订单
		List<Record> list1 = Db.find("SELECT to1.startDate,to1.expireDate,to1.spikeid FROM t_bus_order to1 WHERE to1.expireDate>? AND to1.expireDate<? AND to1.isSpike=? AND to1.reason is null ",olddate,nowdate,1);
		if(list1!=null && list1.size()>0){
			for(Record rec : list1){
				int id = rec.getInt("spikeid");
				if(Db.update("UPDATE t_spike_union SET spikeLeft=spikeLeft+1 WHERE id=?",id)!=1){
					throw new RuntimeException("修改库存失败");
				}
			}
		}
	}
	/**
	 * 根据订单号查快递
	 * @param orderNumber
	 * @return 
	 */
	public Record findWuliuByOrderNum(String orderNumber) {
		return Db.findFirst("SELECT * FROM t_bus_order_logistics WHERE orderCode = ?",orderNumber);
	}
	/**
	 * 根据订单号查询  支付成功的订单号
	 * @return 
	 */
	public List<Record> queryOrderByOrderNum(String orderNum) {
		return Db.find("SELECT * FROM t_bus_user_pay_orderid WHERE  fromOrderNum=? ",orderNum);
	}
	/**
	 * 查询所有待收货普通订单
	 * @return 
	 */
	public List<Order> queryReciveOrder(Date date) {
		
		return Order.me().find("SELECT * FROM t_bus_order WHERE orderState=6 AND payDate<? AND tuistate=0 ",date);
	}
	/**
	 * 查询所有待收货兑换订单
	 * @return 
	 */
	public List<OrderE> queryReciveExchangeOrder(Date date) {

		return OrderE.me().find("SELECT * FROM t_bus_order_act WHERE orderState=6 AND payDate<? AND tuistate=0 ",date);
	}
	/**
	 * 查询用户评论
	 * @param int1
	 * @return 
	 */
	public List<Record> findCommentByuserid(Integer id) {
		
		String sql = "SELECT * FROM t_bus_order_eval WHERE userid = ?";
		return Db.find(sql, id);
	}
	/**
	 * 查找评论图片
	 * @param object
	 * @return 
	 */
	public List<Record> findImageByLunBoNum(String str) {
		
		String sql = "SELECT * FROM t_bus_order_eval_images WHERE LunBoNum = ?";
		return Db.find(sql, str);
	}
	/**
	 * 根据订单号查询兑换商品详情
	 * @return 
	 */
	public Record findExchanegGoodByOrderNum(String orderNum,int id) {
		
		String sql = "SELECT ta.orderNum,tg.*,ts.* "
				+ "FROM t_bus_order_act ta "
				+ "LEFT JOIN t_bus_ege_goods tg ON ta.goodsid = tg.id "
				+ "LEFT JOIN t_bus_ege_goods_spec ts ON ts.id = ta.specsid "
				+ "WHERE ta.orderNum = ? AND ta.userid=? AND ta.orderState=? ";
		return Db.findFirst(sql, orderNum,id,OrderCode.OrderState.CANCEL);
	}
	
	/**
	 * 根据订单号查询团购商品详情
	 * @return 
	 */
	public Record findGroupGoodByOrderNum(String orderNum,int id) {
		
		String sql = "SELECT ta.orderNum,tg.* "
				+ "FROM t_bus_order_gb ta "
				+ "LEFT JOIN t_bus_goods tg ON ta.goodsid = tg.id "
				+ "WHERE ta.orderNum = ? AND ta.userid=? AND ta.orderState=? ";
		return Db.findFirst(sql, orderNum,id,OrderCode.OrderState.CANCEL);
	}
	
	
	/**
	 * 根据specids查找商品spec信息
	 * @param specsidss
	 * @return 
	 */
	public List<Record> findSpecByids(String specsidss) {
		String sql = "SELECT tl.*,tg.thumb FROM t_bus_goods_sale tl "
				+ "LEFT JOIN t_bus_goods tg ON tg.id=tl.goodsid "
				+ "WHERE tl.id IN ("+specsidss+")";
		return Db.find(sql);
	}
	/**
	 * 根据兑换商品id查找
	 * @param id
	 * @return 
	 */
	public Record findExchangeByid(int id) {
		String sql = "SELECT *,ts.id as sid FROM t_bus_ege_goods_spec ts "
				+ "LEFT JOIN t_bus_ege_goods tg ON tg.id = ts.goodId "
				+ "WHERE ts.id = ? ";
		return Db.findFirst(sql,id);
	}
	/**
	 * 查找商品id找价格
	 * @param int1
	 * @return 
	 */
	public Record findSpikeByGoodid(Integer id) {
		return Db.findFirst("SELECT spikePrice FROM t_spike_union WHERE goodsId=?", id);
	}
	/**
	 * 删除订单
	 * @param orderNum
	 * @param isRedeem
	 * @param id
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public void delete(String orderNum, String isRedeem, int id) throws Exception {
		if("1".equals(isRedeem)){
			//兑换订单 
			OrderE order = getExchangeOrderByOrderNum(id,orderNum);
			if(order!=null){
				//1.判断订单状态是否为“待收货”状态
				int orderState = order.getInt("orderState");
				if(orderState==OrderCode.OrderState.FINISH){
					Date time1 = new Date();
					time1 = order.getTimestamp("expireDate");
					Date time2 = new Date();
					if(time1.getTime()>time2.getTime()){
						throw new Exception("此订单不允许删除");
					}
				}
				//2.删除订单操作，并记录日志
				order.set("orderState", OrderCode.OrderState.DELETE);
				if(order.update()){
					try {
						logE(order.getStr("orderNum"),OrderCode.OrderLogType.DELETE,"用户", OrderCode.OrderLogType.DELETE_ACTION, "订单已删除");
					} catch (Exception e) {
						logger.info(">>>>>>>>>兑换日志记录失败");
						throw new Exception("网络繁忙...，请稍后重试");
					}
				}else{
					throw new Exception("删除订单失败");
				}
			}else{
				throw new Exception("订单不存在");
			}
		}else if("0".equals(isRedeem)){
			Order order = getOrderByOrderNum(id,orderNum);
			if(order!=null){
				//1.判断订单状态是否为“待收货”状态
				int orderState = order.getInt("orderState");
				if(orderState==OrderCode.OrderState.FINISH){
					Date time1 = new Date();
					time1 = order.getTimestamp("expireDate");
					Date time2 = new Date();
					if(time1.getTime()>time2.getTime()){
						throw new Exception("此订单当前不允许删除");
					}
				}
				//2.删除订单操作，并记录日志
				order.set("orderState", OrderCode.OrderState.DELETE);
				if(order.update()){
					try {
						log(order.getStr("orderNum"),OrderCode.OrderLogType.DELETE,"用户", OrderCode.OrderLogType.DELETE_ACTION, "订单已删除");
					} catch (Exception e) {
						logger.info(">>>>>>>>>日志记录失败");
						throw new Exception("网络繁忙...，请稍后重试");
					}
				}else{
					
					throw new Exception("删除订单失败");
				}
			}else{
				throw new Exception("订单不存在！");
			}
		}else{
			OrderG order = getOrderGByOrderNum(id,orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				if(orderState != OrderCode.OrderState.NORMAL){
					//不是待支付订单不可删除
					throw new Exception("此订单当前不允许删除");
				}
				//未支付订单未到期或取消  不可删除
				Date time1 = new Date();
				time1 = order.getTimestamp("expireDate");
				Date time2 = new Date();
				if(time1.getTime()>time2.getTime()){
					throw new Exception("此订单当前不允许删除");
				}
				//2.删除订单操作，并记录日志
				order.set("orderState", OrderCode.OrderState.DELETE);
				if(order.update()){
					OrderGLog orderLog = new OrderGLog();
					orderLog.set("orderNum", orderNum)
							.set("type", OrderCode.OrderLogType.DELETE)
							.set("user", id)
							.set("action", OrderCode.OrderLogType.DELETE_ACTION)
							.set("content", OrderCode.OrderLogType.DELETE_CONTECT);
					if(orderLog.save()){
						
					}else{
						logger.info(">>>>>>>>>团购日志记录失败");
						throw new Exception("网络繁忙...，请稍后重试");
					}
				}else{
					throw new Exception("删除失败");
				}
			}else{
				throw new Exception("订单不存在");
			}
			
		}
	}
	/**
	 * 根据订单号查团购订单
	 * @param int1
	 * @param orderNum
	 * @return
	 */
	public OrderG getOrderGByOrderNum(Integer id, String orderNum) {
		String sql = "SELECT to1.* FROM "
				+ " t_bus_order_gb to1 "
				+ " WHERE to1.orderNum=? AND to1.userid=? ";
		//查找
		return OrderG.me().findFirst(sql,orderNum,id);
	}
	/**
	 * 签收团购订单
	 * @param currentUser
	 * @param orderNum
	 * @return -1 订单不存在 1签收成功 2签收失败
	 */
	public int receiveOrderG(User user, String orderNum) {
		System.out.println(user);
		System.out.println(orderNum);
		//查找有无此订单
		String sql = "SELECT * FROM t_bus_order_gb WHERE orderState=? "
				+ " AND tuistate=? AND orderNum=? AND userid=? ";
		OrderG order = OrderG.me().findFirst(sql,OrderCode.OrderState.SHOU,OrderCode.OrderTuiState.NO_REFUND,orderNum,user.getInt("id"));
		if(order!=null){
			
			//3.签收订单操作，并记录日志
			try {
				//在service中进行订单签收(修改订单状态、商品返利、用户是否升级为黄金会员)的一系列操作,保证事务回滚
				receiveOrderG(order,user);
				return 1;
			} catch (Exception e) {
				e.printStackTrace();
				return 2;
			}
			
		}else{
			return -1;
		}
		
	}
	/**
	 * 用户签收团购订单
	 */
	@Before(Tx.class)
	public void receiveOrderG(OrderG order,User user) throws Exception {
		//更新订单状态
		order.set("orderState", OrderCode.OrderState.CANCEL).set("signDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
		if(order.update()){
			log(order.getStr("orderNum"),OrderCode.OrderLogType.GET,"用户", OrderCode.OrderLogType.GET_ACTION, "已取货，感谢您的购物，欢迎再次光临！");
			//根据用户所购买的商品，进行拓客处理   赠送积分等
			giveSppoint(order,user);
			//赠送
			rebateG(order);
		}else{
			throw new Exception("订单接收失败！");
		}
	}
	
	/**
	 * 拓客  （团购订单）
	 * @param order
	 * @param user
	 * @throws Exception
	 */
	private void rebateG(OrderG order) throws Exception{
		String orderNum = order.getStr("orderNum");
		//下单用户id
		int userid =order.getInt("userid");
		//下单用户
		User user = User.me().findById(userid);
		//查询订单商品列表
		List<Record> goodsList = Db.find("SELECT * FROM t_bus_order_list WHERE orderNum=?", order.getStr("orderNum"));
		
		//所购开启拓客商品总额
		double totalAmount = 0;
		
		//用户注册时邀请人ID
		int inviteUserid = user.getInt("inviteid");
		//直接邀请人
		User userInvite=null;
		//间接邀请人用户id
		int userInvite_UserId = 0;
		if (inviteUserid!=0) {
			userInvite = User.me().findById(inviteUserid);
			userInvite_UserId = userInvite.getInt("inviteid");
		}
	
		
		//归属于那个营业部 			//营业部在t_auth_admin_seller表中的id
		int toBossOneId = user.getInt("toBossOneId");
		//用户归属于那个分公司 	//分公司在t_dict_store表中的id
		int toBossTwoId = user.getInt("toBossTwoId");
		//用户归属于那个公司//公司在t_bus_seller表中的id
		int toBossThreeId = user.getInt("toBossThreeId");
		
		//拓客日志SQL
		String logSql = "INSERT INTO t_bus_order_toker_log(orderNum,goodsid,amount,onePoint,oneDetion,oneDcount,twoPoint,twoDetion,twoDcount,"
				+ "threePoint,threeDetion,threeDcount,fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,fiveDcount) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		
	
		
			//拓客日志列表1 
			//拓客分成2（用户有邀请人，一级、二级、所属营业部、分公司、公司分润）
			List<Object[]> logParams1 = new ArrayList<Object[]>();
			//拓客分成1（用户没有邀请人，所属营业部、分公司、公司分润）
			double[] rebate1 = new double[15];
			
			//订单多商品多分润实际累计日志
			List<Object[]> logParamsTotal = new ArrayList<Object[]>();
		/*	****************#########################**************装载对象****start*******##########################*******************************************/
			//遍历所有商品
			for(Record goods : goodsList){
				//商品是否参与拓客  0 不拓客，1拓客
				if(goods.getInt("isToker")==1){
					//商品id
					int goodsid = goods.getInt("goodsid");
					//商品总金额
					double amount = goods.getDouble("amount");
					
					//累计本单中所有开启返利的商品的消费金额
					totalAmount = DoubleKit.add(totalAmount, amount);
					
					//一级返利的积分值
					double onePoint = goods.getDouble("onePoint");
					//一级返利的抵扣券
					double oneDetion = goods.getDouble("oneDetion");
					//一级返利的惠券
					double oneDcount = goods.getDouble("oneDcount");
					
					//二级返利的积分值
					double twoPoint = goods.getDouble("twoPoint");
					//二级返利的抵扣券
					double twoDetion = goods.getDouble("twoDetion");
					//二级返利的惠券
					double twoDcount = goods.getDouble("twoDcount");
					
					//'营业部服务所得的积分值',
					double threePoint = goods.getDouble("threePoint");
					//'营业部服务所得的抵扣券',
					double threeDetion = goods.getDouble("threeDetion");
					//'营业部服务所得的惠券',
					double threeDcount = goods.getDouble("threeDcount");
					
					//'分公司培训所得的积分值'
					double fourPoint = goods.getDouble("fourPoint");
					// '分公司培训所得的抵扣券',
					double fourDetion = goods.getDouble("fourDetion");
					//'分公司培训所得的惠券',
					double fourDcount = goods.getDouble("fourDcount");
					
					//'公司管理所得的积分值',
					double fivePoint = goods.getDouble("fivePoint");
					//'公司管理所得的抵扣券',
					double fiveDetion = goods.getDouble("fiveDetion");
					//'公司管理所得的惠券',
					double fiveDcount = goods.getDouble("fiveDcount");
					
					
					
					//邀请人存在时
					if(inviteUserid!=0) {
						//一级返利累加
						rebate1[0] = DoubleKit.add(rebate1[0], onePoint);
						rebate1[1] = DoubleKit.add(rebate1[1], oneDetion);
						rebate1[2] = DoubleKit.add(rebate1[2], oneDcount);
						
						//间接邀请人存在时
						if (userInvite_UserId!=0) {
							//二级返利累加
							rebate1[3] = DoubleKit.add(rebate1[3], twoPoint);
							rebate1[4] = DoubleKit.add(rebate1[4], twoDetion);
							rebate1[5] = DoubleKit.add(rebate1[5], twoDcount);
						} else {
							//二级返利累加
							rebate1[3] = 0;
							rebate1[4] = 0;
							rebate1[5] = 0;
						}
					} else {//邀请人不存在
						//一级返利累加
						rebate1[0] = 0;
						rebate1[1] = 0;
						rebate1[2] = 0;
						//二级返利累加
						rebate1[3] = 0;
						rebate1[4] = 0;
						rebate1[5] = 0;
						 onePoint = 0;
						oneDetion = 0;
						oneDcount = 0;
						twoPoint = 0;
						twoDetion = 0;
						twoDcount = 0;
					}
					
					
					//如果所属营业部存在则累计
					if (toBossOneId!=0) {
						//营业部服务所得累加
						rebate1[6] = DoubleKit.add(rebate1[6], threePoint);
						rebate1[7] = DoubleKit.add(rebate1[7], threeDetion);
						rebate1[8] = DoubleKit.add(rebate1[8], threeDcount);
					} else {
						//营业部服务所得累加
						rebate1[6] = 0;
						rebate1[7] = 0;
						rebate1[8] = 0;
						threePoint = 0;
						threeDetion = 0;
						threeDcount = 0;
					}
					 
					//如果所属分公司存在 则累加
					if (toBossTwoId!=0) {
						//分公司培训所得累加
						rebate1[9] = DoubleKit.add(rebate1[9], fourPoint);
						rebate1[10] = DoubleKit.add(rebate1[10], fourDetion);
						rebate1[11] = DoubleKit.add(rebate1[11], fourDcount);
					} else {
						//分公司培训所得累加
						rebate1[9] = 0;
						rebate1[10] = 0;
						rebate1[11] = 0;
						fourPoint= 0;
						fourDetion= 0;
						 fourDcount= 0;
					}
					
					//如果所属公司存在 则累加
					if (toBossThreeId!=0) {
						//公司管理所得累加
						rebate1[12] = DoubleKit.add(rebate1[12], fivePoint);
						rebate1[13] = DoubleKit.add(rebate1[13], fiveDetion);
						rebate1[14] = DoubleKit.add(rebate1[14], fiveDcount);
					} else {
						//公司管理所得累加
						rebate1[12] = 0;
						rebate1[13] = 0;
						rebate1[14] = 0;
						 fivePoint = 0;
						 fiveDetion = 0;
						 fiveDcount = 0;
					}
				
					
					//邀请人存在时或不存在时订单里每个商品拓客日志
					
					logParams1.add(new Object[]{orderNum,goodsid,amount,onePoint,oneDetion,oneDcount,twoPoint,
								twoDetion,twoDcount,threePoint,threeDetion,threeDcount,fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,fiveDcount});
					
				}
			}
			
			//订单拓客日志SQL
			String logSqlTotal = "INSERT INTO t_bus_order_toker_user_log(orderNum,totalAmount,totalPoint,totalDetion,totalDcount,"
					+ "userid,oneUserid,twoUserid,threeUserid,fourUserid,"
					+ "fiveUserid,onePoint,oneDetion,oneDcount,twoPoint,"
					+ "twoDetion,twoDcount,threePoint,threeDetion,threeDcount,"
					+ "fourPoint,fourDetion,fourDcount,fivePoint,fiveDetion,"
					+ "fiveDcount) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";


			
			
			AuthSeller authSeller=null;//营业部对象
			Store store =null;//分公司对象
			Seller seller=null;//公司对象
			int threeUserid = 0;
			int fourUserid = 0;
			int fiveUserid = 0;
			
			User userAuthSeller=null;//营业部在t_bus_user表的对象
			User userStore =null;//分公司在t_bus_user表的对象
			User userSeller=null;//公司在t_bus_user表的对象
			
			//营业部对象
			if (toBossOneId!=0) {
				authSeller= AuthSeller.me().findById(toBossOneId);
				//在t_bus_user表的id
				threeUserid=authSeller.getInt("tokerUserid");
				userAuthSeller= User.me().findById(threeUserid);
			}
			//分公司对象
			if (toBossTwoId!=0) {
				store= Store.me().findById(toBossTwoId);
				//在t_bus_user表的id
				fourUserid = store.getInt("tokerUserid");
				userStore= User.me().findById(fourUserid);
			}
			//公司对象
			if (toBossThreeId!=0) {
				seller= Seller.me().findById(toBossThreeId);
				//在t_bus_user表的id
				fiveUserid = seller.getInt("tokerUserid");
				userSeller= User.me().findById(fiveUserid);
			}
			double totalPoint =DoubleKit.add(rebate1[0]+rebate1[3],rebate1[6]+rebate1[9]+rebate1[12]) ;
			double totalDetion =DoubleKit.add(rebate1[1]+rebate1[4],rebate1[7]+rebate1[10]+rebate1[13]) ;
			double totalDcount =DoubleKit.add(rebate1[2]+rebate1[5],rebate1[8]+rebate1[11]+rebate1[14]) ;
			
			//总订单不在记录商品标号
			logParamsTotal.add(new Object[]{orderNum,totalAmount,totalPoint,totalDetion,totalDcount,userid,inviteUserid,userInvite_UserId,threeUserid,fourUserid,fiveUserid,rebate1[0],rebate1[1],rebate1[2],rebate1[3],
					rebate1[4],rebate1[5],rebate1[6],rebate1[7],rebate1[8],rebate1[9],rebate1[10],rebate1[11],rebate1[12],rebate1[13],rebate1[14]});
			
			/*	****************#########################**************装载对象****end*******##########################*******************************************/
			
			//如果消费的返利商品金额为0，则不处理
			if(totalAmount==0)return;
			
			//用户没有邀请人时
			if(inviteUserid==0){
				//如果用户注册时没有邀请人，则本次购物所有返利将由营业部、公司、分公司享利
				//1.如果所属营业部不为空，修改营业部用户的积分、抵扣券、惠券
				
				//营业部对象 和营业部所在用户表t_bus_user的id不为空时
				if (toBossOneId!=0 &&threeUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[6],rebate1[7],rebate1[8],threeUserid)!=1){
						throw new Exception("用户（用户ID："+threeUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录营业部用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							threeUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_THREE,orderNum,totalAmount,
							rebate1[6],rebate1[7],rebate1[8],userAuthSeller.get("sppoint"),userAuthSeller.get("jkpoint"),userAuthSeller.get("jypoint"),
							1,"营业部服务奖励",new Date());
				}
				//分公司对象 和分公司所在用户表t_bus_user的id不为空时
				if (toBossTwoId!=0&&fourUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[9],rebate1[10],rebate1[11],fourUserid)!=1){
						throw new Exception("用户（用户ID："+fourUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录分公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fourUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FOUR,orderNum,totalAmount,
							rebate1[9],rebate1[10],rebate1[11],userStore.get("sppoint"),userStore.get("jkpoint"),userStore.get("jypoint"),
							1,"分公司培训奖励",new Date());
				}
				//公司对象 和公司所在用户表t_bus_user的id不为空时
				if (toBossThreeId!=0&&fiveUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[12],rebate1[13],rebate1[14],fiveUserid)!=1){
						throw new Exception("用户（用户ID："+fiveUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fiveUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FIVE,orderNum,totalAmount,
							rebate1[12],rebate1[13],rebate1[14],userSeller.get("sppoint"),userSeller.get("jkpoint"),userSeller.get("jypoint"),
							1,"公司管理奖励",new Date());
				}
				
			}else{
				
				
				//邀请人存在时
				if(inviteUserid!=0) {
					//一级返利累加
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[0],rebate1[1],rebate1[2],inviteUserid)!=1){
						throw new Exception("用户（用户ID："+inviteUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录直接邀请人用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							inviteUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_ONE,orderNum,totalAmount,
							rebate1[0],rebate1[1],rebate1[2],userInvite.get("sppoint"),userInvite.get("jkpoint"),userInvite.get("jypoint"),
							1,"邀请人奖励",new Date());
					
					//间接邀请人存在时
					if (userInvite_UserId!=0) {
						//间接邀请人对象
						User inviteUser2 = User.me().findById(userInvite_UserId);
						//二级返利累加
						//此处使用行锁定的方式更新，防止并发
						if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[3],rebate1[4],rebate1[5],userInvite_UserId)!=1){
							throw new Exception("用户（用户ID："+inviteUserid+"）更新积分、抵扣券、惠券时出错！");
						}
						//2.记录直接邀请人用户积分、抵扣券、惠券变动日志（记录订单号）
						Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
								+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
								+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
								userInvite_UserId,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_TWO,orderNum,totalAmount,
								rebate1[3],rebate1[4],rebate1[5],inviteUser2.get("sppoint"),inviteUser2.get("jkpoint"),inviteUser2.get("jypoint"),
								1,"间接邀请人奖励",new Date());
					} 
					
				}

				//如果用户注册时没有邀请人，则本次购物所有返利将由营业部、公司、分公司享利
				//1.如果所属营业部不为空，修改营业部用户的积分、抵扣券、惠券
				//营业部对象 和营业部所在用户表t_bus_user的id不为空时
				if (toBossOneId!=0 &&threeUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[6],rebate1[7],rebate1[8],threeUserid)!=1){
						throw new Exception("用户（用户ID："+threeUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录营业部用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							threeUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_THREE,orderNum,totalAmount,
							rebate1[6],rebate1[7],rebate1[8],userAuthSeller.get("sppoint"),userAuthSeller.get("jkpoint"),userAuthSeller.get("jypoint"),
							1,"营业部服务奖励",new Date());
				}
				//分公司对象 和分公司所在用户表t_bus_user的id不为空时
				if (toBossTwoId!=0&&fourUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[9],rebate1[10],rebate1[11],fourUserid)!=1){
						throw new Exception("用户（用户ID："+fourUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录分公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fourUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FOUR,orderNum,totalAmount,
							rebate1[9],rebate1[10],rebate1[11],userStore.get("sppoint"),userStore.get("jkpoint"),userStore.get("jypoint"),
							1,"分公司培训奖励",new Date());
				}
				//公司对象 和公司所在用户表t_bus_user的id不为空时
				if (toBossThreeId!=0&&fiveUserid!=0) {
					//此处使用行锁定的方式更新，防止并发
					if(Db.update("UPDATE t_bus_user SET sppoint=sppoint+?,jkpoint=jkpoint+?,jypoint=jypoint+? WHERE id=?",rebate1[12],rebate1[13],rebate1[14],fiveUserid)!=1){
						throw new Exception("用户（用户ID："+fiveUserid+"）更新积分、抵扣券、惠券时出错！");
					}
					//2.记录公司用户积分、抵扣券、惠券变动日志（记录订单号）
					Db.update("INSERT INTO t_bus_user_value_log(userid,type,flag,fromOrderNum,orderMoney,sppoint,dedu,coupon,"
							+ "sppointHistory,deduHistory,couponHistory,data,`describe`,createDate) "
							+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
							fiveUserid,UserCode.UserLevelLogType.ONE,UserCode.UserValueLogFlag.CONSUME_FIVE,orderNum,totalAmount,
							rebate1[12],rebate1[13],rebate1[14],userSeller.get("sppoint"),userSeller.get("jkpoint"),userSeller.get("jypoint"),
							1,"公司管理奖励",new Date());
				}
				
				
			}
			//3.记录拓客日志,已商品列表为主的
			Db.batch(logSql, parseParams(logParams1), logParams1.size());
			//3.记录拓客日志,已订单总额为主的日志
			Db.batch(logSqlTotal, parseParams(logParamsTotal), logParamsTotal.size());

	}
	
	/**
	 * 更改退款订单状态
	 * @param orderNum订单号
	 * @param tuistate退款状态
	 * @param orderState需要更改的订单状态
	 * @param userid用户ID
	 * @param type订单日志记录操作类型
	 * @param user订单日志记录操作用户
	 * @param action订单日志记录描述
	 * @param content订单日志记录内容
	 * @param refundReason申请退款原因
	 * @return
	 * @throws Exception
	 */
	@Before(Tx.class)
	public boolean updateRefund(String orderNum,int tuistate,int orderState, int userid,int type,String user,String action,String content,String refundReason) throws Exception {
		String str = orderNum.subSequence(0, 1).toString();
		//分类查询订单
		if("G".equals(str)){
			Order order = getOrderListByMergerOrderNum(userid,orderNum);
			if(order==null){
				logger.error("申请退款的普通订单不存在");
	    		return false;
			}else if(order.getInt("orderState")==orderState&&order.getInt("tuistate")==tuistate){
				logger.info("操作过于频繁，请刷新后重试");
				return false;
			}
			//更改订单状态为审核中
			if (order.set("tuistate", tuistate).set("orderState", orderState).update()) {
				log(orderNum,type,user,action,content);
				OrderRefund orderRefund=queryOrderRefundByOrderNum(orderNum);
				if (orderRefund==null) {
					//退款记录
					Record record = new Record();
					String refundNum="GT"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
					record.set("orderNum", orderNum)
						.set("refundNum", refundNum)
						.set("type", 1)
						.set("amount", order.getDouble("amount"))
						.set("state", tuistate)
						.set("refundReason",refundReason);
					if(Db.save("t_bus_order_refund", record)){
						if (order.getInt("orderState")==OrderCode.OrderState.CANCEL||order.getInt("orderState")==OrderCode.OrderState.EXPIRE) {
							User userUser=User.me().findById(userid);
							Double spoint=order.getDouble("sppoint");
							Double dedu=order.getDouble("jkpoint");
							Double coupon=order.getDouble("jypoint");
							//更改前的值
							Double sppointHistory = userUser.getDouble("sppoint");
							Double deduHistory = userUser.getDouble("jkpoint");
							Double couponHistory = userUser.getDouble("jypoint");
							Double ecouponHistory = userUser.getDouble("ecoupon");
							//更改后
							Double newSpoint = DoubleKit.sub(sppointHistory, spoint);
							Double newJkpoint = DoubleKit.sub(deduHistory, dedu);
							Double newJypoint = DoubleKit.sub(couponHistory, coupon);
							Double newEcoupon = DoubleKit.sub(ecouponHistory, 0.00);
							//修改
							userUser.set("sppoint", newSpoint);
							userUser.set("jkpoint", newJkpoint);
							userUser.set("jypoint", newJypoint);
							userUser.set("ecoupon", newEcoupon);
							if(userUser.update()){
								//记录
								Double orderMoney=order.getDouble("amount");
								Record re=new Record()
								.set("userid", userid)
								.set("type",2)
								.set("flag",16)
								.set("fromOrderNum",orderNum)
								.set("data",1)
								.set("describe","取消订单扣减")
								.set("createDate", new Date())
								.set("sppoint", spoint)
								.set("sppointHistory", sppointHistory)
								.set("dedu", dedu)
								.set("deduHistory", deduHistory)
								.set("coupon", coupon)
								.set("couponHistory", couponHistory)
								.set("ecoupon", 0.00)
								.set("ecouponHistory", ecouponHistory)
								.set("orderMoney", orderMoney);
								if(!Db.save("t_bus_user_value_log", re)){
									throw new Exception("保存财富日志表失败");
								}
								logger.info("申请退款成功，等待审核");
								return true;
							}
							throw new Exception("更改用户财富失败");
						}
						logger.info("申请退款成功，等待审核");
						return true;
					}else {
						throw new RuntimeException("普通订单退款记录添加异常");
					}
				}else {
					if (orderRefund.set("state", tuistate).update()) {
						if (tuistate==4) {
							if (updateUserValueByRefund(orderNum)) {
								logger.info("普通订单退款记录修改成功");
								return true;
							}else {
								throw new RuntimeException("普通订单退款拓客扣减奖励异常");
							}
						}else {
							return true;
						}
					}else {
						throw new RuntimeException("普通订单退款记录修改异常");
					}
					
				}
			}else {
				logger.error("修改订单退款状态失败");
				return false;
			}
		}else if("D".equals(str)){
			OrderE order = getExchangeOrdersByOrderNum(userid,orderNum);
			if(order==null){
				logger.error("申请退款的兑换订单不存在订单不存在");
	    		return false;
			}
			//更改订单状态为审核中
			if (order.set("tuistate", OrderCode.OrderTuiState.APPLYREFUNDING).update()) {
				logger.info("兑换订单申请退款成功，等待审核");
				return true;
			}else {
				logger.error("修改兑换订单退款状态失败");
				return false;
			}
		}else {
			logger.error("订单不存在或则订单类型错误 ");
			return false;
		}
	}
	
	/**
	 * 执行用户取消订单的退款
	 */
	@Before(Tx.class)
	public void doRefund() {
		//查询所有退款审核完成的订单
		String sql = "SELECT * FROM t_bus_order WHERE tuistate=? and payState=? AND orderState!=? ";
		List<Order> list= Order.me().find(sql,OrderCode.OrderTuiState.CHECKREFUND,
				OrderCode.OrderPayState.HAD_PAY,OrderCode.OrderState.DELETE);
		System.out.println("自动退款"+list);
		if (list!=null&&list.size()>0) {
			for (Order order : list) {
				//获取参数
				int payMethod=order.getInt("paytype");
				String orderNum=order.get("orderNum");
				System.out.println("待退款订单:"+orderNum);
				int orderState=order.getInt("orderState");
				Double amount=order.getDouble("amount");
				int userid=order.getInt("userid");
				User user = User.me().findById(userid);
				
				if (!order.set("tuistate", OrderCode.OrderTuiState.REFUNDING).update()) {
					logger.error("修改订单状态为退款中失败");
					try {
						if (updateRefund(orderNum, OrderCode.OrderTuiState.REFUNDEXCEPTION, orderState, userid, OrderCode.OrderLogType.REFUNDEXCEPTION, "轮询退款", "修改退款状态为退款中异常", "修改退款状态为退款中异常","")) {
							logger.error("用户取消订单退款失败,已记录异常"+orderNum);
						}else {
							logger.error("用户取消订单退款失败,未能记录异常"+orderNum);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						logger.error("用户取消订单退款失败,未能记录异常"+orderNum);
						e.printStackTrace();
					}
					continue;
				}
				OrderRefund orderRefund=queryOrderRefundByOrderNum(orderNum);
				String refundNum="";
				if (orderRefund!=null) {
					refundNum=orderRefund.getStr("refundNum");
				}
				//定义返回值，根据付款方式执行对应退款方法
				int count=0;
				if (payMethod==OrderCode.OrderPayMethod.WEIXIN) {
					count= Refund.weiXinR(orderNum,amount,userid);
				}else if (payMethod==OrderCode.OrderPayMethod.ALIPAY) {
					count= Refund.alipayRefund(orderNum,amount,"取消订单退款");
				}else if (payMethod==OrderCode.OrderPayMethod.BALANCE1) {
					count= Refund.BALANCE1(orderNum,user,amount,"取消订单退款");
				}else {
					count=100;
				}
				//异常记录日志
				Record re = new Record();
				re.set("orderNum", orderNum)
				  .set("refundNum",refundNum)
				  .set("type",7)
				  .set("user","用户"+userid)
				  .set("action","用户取消订单退款异常");
				
				switch (count) {
				case 0:
					try {
						refundOrderDeal(user,amount);
						if (updateRefund(orderNum,OrderCode.OrderTuiState.REFUNDED,OrderCode.OrderState.REFUNDED,userid,OrderCode.OrderLogType.REFUNDED,"轮询","取消订单退款","取消订单退款成功","")) {
							logger.info("用户取消订单退款完成"+orderNum);
						}else {
							re.set("content","退款成功，更新退款状态或拓客奖励扣减异常"+orderNum);
							if(!Db.save("t_bus_order_exception_log", re)){
								logger.error("取消订单退款异常，订单号："+orderNum);
							}
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						re.set("content","退款成功，更新退款状态异常"+orderNum);
						if(!Db.save("t_bus_order_exception_log", re)){
							logger.error("取消订单退款异常记录失败，订单号："+orderNum);
						}
					}
					break;
				case 1:
					re.set("content","退款请求准备异常"+orderNum);
					break;
				case 2:
					re.set("content","退款请求发送异常"+orderNum);
					break;
				case 3:
					re.set("content","退款请求发送成功，退款失败"+orderNum);
					break;
				case 4:
					re.set("content","修改用户余额失败"+orderNum);
					break;
				case 5:
					re.set("content","用户余额记录更新失败"+orderNum);
					break;
				case 6:
					re.set("content","订单操作记录更新失败"+orderNum);
					break;
				case 100:
					re.set("content","退款方式异常"+orderNum);
					break;	
					
				default:
					break;
				}
				if (count!=0) {
					if(!Db.save("t_bus_order_exception_log", re)){
						logger.error("取消订单退款异常，订单号："+orderNum);
					}
					try {
						if (updateRefund(orderNum, OrderCode.OrderTuiState.REFUNDEXCEPTION, orderState, userid, OrderCode.OrderLogType.REFUNDEXCEPTION, "轮询退款", "退款异常", re.getStr("content"),"")) {
							logger.error("用户取消订单退款失败,已记录异常"+orderNum);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
	}
	
	/**
	 * 根据订单号查询退款记录
	 * @param orderNum
	 * @return
	 */
	public OrderRefund queryOrderRefundByOrderNum(String orderNum) {
		return OrderRefund.me().findFirst("SELECT * FROM t_bus_order_refund where orderNum=?", orderNum);
	}
	/*
	 * 检查秒杀订单是否过期
	 */
	public int checkSpikeOrderDate(String id, String[] times) {
		
		
		//根据下单时间
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT ");
		sb.append("* ");
		sb.append("FROM t_spike_list tl ");
		sb.append("RIGHT JOIN t_spike_union tu ON tl.id = tu.listId ");
		sb.append("LEFT JOIN t_spike_time tt ON tt.id = tl.timeid ");
		sb.append("WHERE 1=1 ");
		sb.append("AND ? BETWEEN tl.start AND tl.stop ");
		sb.append("AND tu.goodsId = ?  ");
		sb.append("AND ? BETWEEN tt.begin AND tt.end ");
		List<Record> find = Db.find(sb.toString(),times[0],id,times[1]);
		if(find == null ){
			return -1;
		}
		return 1;
		
	}
	
	/**
	 * 根据订单号查询出该订单的拓客奖励日志列表
	 * @param orderNum订单号
	 * @return
	 */
	public static List<Record> queryValueLogByOrderNum(String orderNum) {
		return Db.find("SELECT * FROM t_bus_user_value_log WHERE fromOrderNum=? AND FLAG IN (?,?,?,?,?)",orderNum,UserCode.UserValueLogFlag.CONSUME_ONE
				,UserCode.UserValueLogFlag.CONSUME_TWO
				,UserCode.UserValueLogFlag.CONSUME_THREE
				,UserCode.UserValueLogFlag.CONSUME_FOUR
				,UserCode.UserValueLogFlag.CONSUME_FIVE);
	}
	
	/**
	 * 根据订单号对已退款的订单的拓客奖励进行扣减并记录日志
	 * @param orderNum订单号
	 * @return
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public boolean updateUserValueByRefund(String orderNum) throws Exception {
		List<Record>logs= queryValueLogByOrderNum(orderNum);
		if (logs!=null&&logs.size()>0) {
			for (Record record : logs) {
				int userid=record.getInt("userid");
				User userUser=User.me().findById(userid);
				Double spoint=record.getDouble("sppoint");
				Double dedu=record.getDouble("dedu");
				Double coupon=record.getDouble("coupon");
				//更改前的值
				Double sppointHistory = userUser.getDouble("sppoint");
				Double deduHistory = userUser.getDouble("jkpoint");
				Double couponHistory = userUser.getDouble("jypoint");
				Double ecouponHistory = userUser.getDouble("ecoupon");
				//更改后
				Double newSpoint = DoubleKit.sub(sppointHistory, spoint);
				Double newJkpoint = DoubleKit.sub(deduHistory, dedu);
				Double newJypoint = DoubleKit.sub(couponHistory, coupon);
				Double newEcoupon = DoubleKit.sub(ecouponHistory, 0.00);
				//修改
				userUser.set("sppoint", newSpoint);
				userUser.set("jkpoint", newJkpoint);
				userUser.set("jypoint", newJypoint);
				userUser.set("ecoupon", newEcoupon);
				if(userUser.update()){
					//记录
					Double orderMoney=record.getDouble("orderMoney");
					Record re=new Record()
					.set("userid", userid)
					.set("type",2)
					.set("flag",17)
					.set("fromOrderNum",orderNum)
					.set("data",1)
					.set("describe","下级订单退款，扣减拓客奖励")
					.set("createDate", new Date())
					.set("sppoint", spoint)
					.set("sppointHistory", sppointHistory)
					.set("dedu", dedu)
					.set("deduHistory", deduHistory)
					.set("coupon", coupon)
					.set("couponHistory", couponHistory)
					.set("ecoupon", 0.00)
					.set("ecouponHistory", ecouponHistory)
					.set("orderMoney", orderMoney);
					if(!Db.save("t_bus_user_value_log", re)){
						throw new Exception("保存财富日志表失败");
					}
				}
			}
			return true;
		}else {
			return true;
		}
	}
	
	/**
	 * 普通订单取消订单退款成功后 扣减总消费金额，检测开团资格，等级变更
	 * @param user  
	 * @param userid
	 * @param money
	 * @param user1
	 * @throws Exception
	 */
	@Before(Tx.class)
	private void refundOrderDeal(User user, Double money) throws Exception {
		int userid = user.getInt("id");
		Double totalMoney=user.getDouble("totalMoney");
		Double newTotalMoney=DoubleKit.sub(totalMoney, money);
		//总消费扣减
		if(Db.update("UPDATE t_bus_user SET totalMoney=? WHERE id=?",newTotalMoney,userid)!=1){
			logger.info("普通订单取消订单退款成功后更改用户表失败");
			throw new Exception("普通订单取消订单退款成功后总消费金额扣减失败");
		}
		
		//查询是否还有开团资格
		Double miniNumMoney=SysConfig.getMiniNumMoney();
		System.out.println("普通订单取消订单退款成功后检测开团资格门槛:"+miniNumMoney);
		if(newTotalMoney.compareTo(miniNumMoney)<0){
			System.out.println("普通订单取消订单退款成功后去关闭开团资格");
			if(Db.update("UPDATE t_bus_user SET createteam = 0 WHERE id=?",userid)!=1){
				throw new Exception("普通订单取消订单退款成功后开团资格关闭失败");
			}
		}
		
		//  更改等级
		//目前用户等级
		int level =  user.getInt("taici");
		if(level!=1){
			//查询达到本消费等级的对应积分
			Record levels = Db.findFirst("SELECT `toMoney` FROM t_bus_user_level_set WHERE `levelCode`=?",level);
			if(levels != null){
				Double levelnum = levels.getDouble("toMoney");
				if(newTotalMoney.compareTo(levelnum)<0){
					//更改用户表等级
					if(Db.update("UPDATE t_bus_user SET taici = ? WHERE id=?",level-1,userid)==1){
						//如果变化  t_bus_user_level_log   记录等级变化日志
						Db.update("INSERT INTO t_bus_user_level_log(userid,fromLevel,toLevel,flag,createDate) VALUES(?,?,?,?,?)", userid,level,level-1,2,new Date());
					}
				}
			}
		}
	}
}